From 7d92700042d76bb9cbe0656cd5d73404d060e3d9 Mon Sep 17 00:00:00 2001 From: Victor Sanni Date: Tue, 14 May 2024 13:46:35 -0700 Subject: [PATCH] Move toggleable to widget layer (#148272) Currently, toggleable exists independently in the material and cupertino libraries. Cupertino's toggleable is a minimal copy of material's, and so it makes sense to have only one toggleable in the widgets layer. This change makes it easier for cupertino's toggleables (switch, radio, checkbox) to potentially have as many capabilities as material toggleables (for example, resolving in different widget states), thus increasing support for the cupertino library. ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [ ] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. [Contributor Guide]: https://github.com/flutter/flutter/wiki/Tree-hygiene#overview [Tree Hygiene]: https://github.com/flutter/flutter/wiki/Tree-hygiene [test-exempt]: https://github.com/flutter/flutter/wiki/Tree-hygiene#tests [Flutter Style Guide]: https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo [Features we expect every widget to implement]: https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/wiki/Tree-hygiene#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/wiki/Chat [Data Driven Fixes]: https://github.com/flutter/flutter/wiki/Data-driven-Fixes --------- Co-authored-by: Pierre-Louis <6655696+guidezpl@users.noreply.github.com> --- packages/flutter/lib/material.dart | 1 - .../flutter/lib/src/cupertino/checkbox.dart | 1 - packages/flutter/lib/src/cupertino/radio.dart | 1 - .../flutter/lib/src/cupertino/toggleable.dart | 244 ------------------ .../flutter/lib/src/material/checkbox.dart | 4 +- packages/flutter/lib/src/material/radio.dart | 4 +- packages/flutter/lib/src/material/switch.dart | 4 +- .../src/{material => widgets}/toggleable.dart | 92 ++++--- packages/flutter/lib/widgets.dart | 1 + .../flutter/test/widgets/toggleable_test.dart | 19 ++ 10 files changed, 89 insertions(+), 282 deletions(-) delete mode 100644 packages/flutter/lib/src/cupertino/toggleable.dart rename packages/flutter/lib/src/{material => widgets}/toggleable.dart (86%) create mode 100644 packages/flutter/test/widgets/toggleable_test.dart diff --git a/packages/flutter/lib/material.dart b/packages/flutter/lib/material.dart index 3f6347c6b5..2aea643d53 100644 --- a/packages/flutter/lib/material.dart +++ b/packages/flutter/lib/material.dart @@ -188,7 +188,6 @@ export 'src/material/time_picker.dart'; export 'src/material/time_picker_theme.dart'; export 'src/material/toggle_buttons.dart'; export 'src/material/toggle_buttons_theme.dart'; -export 'src/material/toggleable.dart'; export 'src/material/tooltip.dart'; export 'src/material/tooltip_theme.dart'; export 'src/material/tooltip_visibility.dart'; diff --git a/packages/flutter/lib/src/cupertino/checkbox.dart b/packages/flutter/lib/src/cupertino/checkbox.dart index b0ba4ce741..a123dc0a8f 100644 --- a/packages/flutter/lib/src/cupertino/checkbox.dart +++ b/packages/flutter/lib/src/cupertino/checkbox.dart @@ -6,7 +6,6 @@ import 'package:flutter/widgets.dart'; import 'colors.dart'; import 'constants.dart'; -import 'toggleable.dart'; // Examples can assume: // bool _throwShotAway = false; diff --git a/packages/flutter/lib/src/cupertino/radio.dart b/packages/flutter/lib/src/cupertino/radio.dart index 52b752c847..fcb6d03b7d 100644 --- a/packages/flutter/lib/src/cupertino/radio.dart +++ b/packages/flutter/lib/src/cupertino/radio.dart @@ -6,7 +6,6 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'colors.dart'; -import 'toggleable.dart'; // Examples can assume: // late BuildContext context; diff --git a/packages/flutter/lib/src/cupertino/toggleable.dart b/packages/flutter/lib/src/cupertino/toggleable.dart deleted file mode 100644 index a5fb38d9a6..0000000000 --- a/packages/flutter/lib/src/cupertino/toggleable.dart +++ /dev/null @@ -1,244 +0,0 @@ -// 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/rendering.dart'; -import 'package:flutter/widgets.dart'; - -/// A mixin for [StatefulWidget]s that implements iOS-themed toggleable -/// controls (e.g.[CupertinoCheckbox]es). -/// -/// This mixin implements the logic for toggling the control when tapped. -/// It does not have any opinion about the visual representation of the -/// toggleable widget. The visuals are defined by a [CustomPainter] passed to -/// the [buildToggleable]. [State] objects using this mixin should call that -/// method from their [build] method. -/// -/// This mixin is used to implement the Cupertino components for -/// [CupertinoCheckbox] controls. -@optionalTypeArgs -mixin ToggleableStateMixin on TickerProviderStateMixin { - - /// Whether the [value] of this control can be changed by user interaction. - /// - /// The control is considered interactive if the [onChanged] callback is - /// non-null. If the callback is null, then the control is disabled and - /// non-interactive. A disabled checkbox, for example, is displayed using a - /// grey color and its value cannot be changed. - bool get isInteractive => onChanged != null; - - /// Called when the control changes value. - /// - /// If the control is tapped, [onChanged] is called immediately with the new - /// value. - /// - /// The control is considered interactive (see [isInteractive]) if this - /// callback is non-null. If the callback is null, then the control is - /// disabled and non-interactive. A disabled checkbox, for example, is - /// displayed using a grey color and its value cannot be changed. - ValueChanged? get onChanged; - - /// The [value] accessor returns false if this control is "inactive" (not - /// checked, off, or unselected). - /// - /// If [value] is true then the control "active" (checked, on, or selected). If - /// tristate is true and value is null, then the control is considered to be - /// in its third or "indeterminate" state.. - bool? get value; - - /// If true, [value] can be true, false, or null, otherwise [value] must - /// be true or false. - /// - /// When [tristate] is true and [value] is null, then the control is - /// considered to be in its third or "indeterminate" state. - bool get tristate; - - /// The most recent [Offset] at which a pointer touched the Toggleable. - /// - /// This is null if currently no pointer is touching the Toggleable or if - /// [isInteractive] is false. - Offset? get downPosition => _downPosition; - Offset? _downPosition; - - void _handleTapDown(TapDownDetails details) { - if (isInteractive) { - setState(() { - _downPosition = details.localPosition; - }); - } - } - - void _handleTap([Intent? _]) { - if (!isInteractive) { - return; - } - switch (value) { - case false: - onChanged!(true); - case true: - onChanged!(tristate ? null : false); - case null: - onChanged!(false); - } - context.findRenderObject()!.sendSemanticsEvent(const TapSemanticEvent()); - } - - void _handleTapEnd([TapUpDetails? _]) { - if (_downPosition != null) { - setState(() { _downPosition = null; }); - } - } - - bool _focused = false; - void _handleFocusHighlightChanged(bool focused) { - if (focused != _focused) { - setState(() { _focused = focused; }); - } - } - - late final Map> _actionMap = >{ - ActivateIntent: CallbackAction(onInvoke: _handleTap), - }; - - /// Typically wraps a `painter` that draws the actual visuals of the - /// Toggleable with logic to toggle it. - /// - /// Consider providing a subclass of [ToggleablePainter] as a `painter`. - /// - /// This method must be called from the [build] method of the [State] class - /// that uses this mixin. The returned [Widget] must be returned from the - /// build method - potentially after wrapping it in other widgets. - Widget buildToggleable({ - FocusNode? focusNode, - ValueChanged? onFocusChange, - bool autofocus = false, - required Size size, - required CustomPainter painter, - }) { - return FocusableActionDetector( - focusNode: focusNode, - autofocus: autofocus, - onFocusChange: onFocusChange, - enabled: isInteractive, - actions: _actionMap, - onShowFocusHighlight: _handleFocusHighlightChanged, - child: GestureDetector( - excludeFromSemantics: !isInteractive, - onTapDown: isInteractive ? _handleTapDown : null, - onTap: isInteractive ? _handleTap : null, - onTapUp: isInteractive ? _handleTapEnd : null, - onTapCancel: isInteractive ? _handleTapEnd : null, - child: Semantics( - enabled: isInteractive, - child: CustomPaint( - size: size, - painter: painter, - ), - ), - ), - ); - } -} - -/// A base class for a [CustomPainter] that may be passed to -/// [ToggleableStateMixin.buildToggleable] to draw the visual representation of -/// a Toggleable. -/// -/// Subclasses must implement the [paint] method to draw the actual visuals of -/// the Toggleable. -abstract class ToggleablePainter extends ChangeNotifier implements CustomPainter { - /// The color that should be used in the active state (i.e., when - /// [ToggleableStateMixin.value] is true). - /// - /// For example, a checkbox should use this color when checked. - Color get activeColor => _activeColor!; - Color? _activeColor; - set activeColor(Color value) { - if (_activeColor == value) { - return; - } - _activeColor = value; - notifyListeners(); - } - - /// The color that should be used in the inactive state (i.e., when - /// [ToggleableStateMixin.value] is false). - /// - /// For example, a checkbox should use this color when unchecked. - Color get inactiveColor => _inactiveColor!; - Color? _inactiveColor; - set inactiveColor(Color value) { - if (_inactiveColor == value) { - return; - } - _inactiveColor = value; - notifyListeners(); - } - - /// The color that should be used for the reaction when [isFocused] is true. - /// - /// Used when the toggleable needs to change the reaction color/transparency, - /// when it has focus. - Color get focusColor => _focusColor!; - Color? _focusColor; - set focusColor(Color value) { - if (value == _focusColor) { - return; - } - _focusColor = value; - notifyListeners(); - } - - /// The [Offset] within the Toggleable at which a pointer touched the Toggleable. - /// - /// This is null if currently no pointer is touching the Toggleable. - /// - /// Usually set to [ToggleableStateMixin.downPosition]. - Offset? get downPosition => _downPosition; - Offset? _downPosition; - set downPosition(Offset? value) { - if (value == _downPosition) { - return; - } - _downPosition = value; - notifyListeners(); - } - - /// True if this toggleable has the input focus. - bool get isFocused => _isFocused!; - bool? _isFocused; - set isFocused(bool? value) { - if (value == _isFocused) { - return; - } - _isFocused = value; - notifyListeners(); - } - - /// Determines whether the toggleable shows as active. - bool get isActive => _isActive!; - bool? _isActive; - set isActive(bool? value) { - if (value == _isActive) { - return; - } - _isActive = value; - notifyListeners(); - } - - @override - bool shouldRepaint(covariant CustomPainter oldDelegate) => true; - - @override - bool? hitTest(Offset position) => null; - - @override - SemanticsBuilderCallback? get semanticsBuilder => null; - - @override - bool shouldRebuildSemantics(covariant CustomPainter oldDelegate) => false; - - @override - String toString() => describeIdentity(this); -} diff --git a/packages/flutter/lib/src/material/checkbox.dart b/packages/flutter/lib/src/material/checkbox.dart index aa69c34a2e..c987d80743 100644 --- a/packages/flutter/lib/src/material/checkbox.dart +++ b/packages/flutter/lib/src/material/checkbox.dart @@ -12,7 +12,6 @@ import 'debug.dart'; import 'material_state.dart'; import 'theme.dart'; import 'theme_data.dart'; -import 'toggleable.dart'; // Examples can assume: // bool _throwShotAway = false; @@ -444,6 +443,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)) { diff --git a/packages/flutter/lib/src/material/radio.dart b/packages/flutter/lib/src/material/radio.dart index f15260c2e7..19bdacf87f 100644 --- a/packages/flutter/lib/src/material/radio.dart +++ b/packages/flutter/lib/src/material/radio.dart @@ -13,7 +13,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; @@ -412,6 +411,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)) { diff --git a/packages/flutter/lib/src/material/switch.dart b/packages/flutter/lib/src/material/switch.dart index 945bdb23d9..2c9e411f76 100644 --- a/packages/flutter/lib/src/material/switch.dart +++ b/packages/flutter/lib/src/material/switch.dart @@ -18,7 +18,6 @@ import 'shadows.dart'; import 'switch_theme.dart'; import 'theme.dart'; import 'theme_data.dart'; -import 'toggleable.dart'; // Examples can assume: // bool _giveVerse = true; @@ -746,6 +745,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 diff --git a/packages/flutter/lib/src/material/toggleable.dart b/packages/flutter/lib/src/widgets/toggleable.dart similarity index 86% rename from packages/flutter/lib/src/material/toggleable.dart rename to packages/flutter/lib/src/widgets/toggleable.dart index 4d1ebbd8fb..45aabf961e 100644 --- a/packages/flutter/lib/src/material/toggleable.dart +++ b/packages/flutter/lib/src/widgets/toggleable.dart @@ -4,10 +4,14 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; -import 'package:flutter/widgets.dart'; -import 'constants.dart'; -import 'material_state.dart'; +import 'actions.dart'; +import 'basic.dart'; +import 'focus_manager.dart'; +import 'framework.dart'; +import 'gesture_detector.dart'; +import 'ticker_provider.dart'; +import 'widget_state.dart'; // Duration of the animation that moves the toggle from one state to another. const Duration _kToggleDuration = Duration(milliseconds: 200); @@ -15,9 +19,9 @@ const Duration _kToggleDuration = Duration(milliseconds: 200); // Duration of the fade animation for the reaction when focus and hover occur. const Duration _kReactionFadeDuration = Duration(milliseconds: 50); -/// A mixin for [StatefulWidget]s that implement material-themed toggleable -/// controls with toggle animations (e.g. [Switch]es, [Checkbox]es, and -/// [Radio]s). +/// A mixin for [StatefulWidget]s that implement toggleable +/// controls with toggle animations (e.g. [Switch]es, [CupertinoSwitch]es, +/// [Checkbox]es, [CupertinoCheckbox]es, [Radio]s, and [CupertinoRadio]s). /// /// The mixin implements the logic for toggling the control (e.g. when tapped) /// and provides a series of animation controllers to transition the control @@ -25,9 +29,6 @@ const Duration _kReactionFadeDuration = Duration(milliseconds: 50); /// representation of the toggleable widget. The visuals are defined by a /// [CustomPainter] passed to the [buildToggleable]. [State] objects using this /// mixin should call that method from their [build] method. -/// -/// This mixin is used to implement the material components for [Switch], -/// [Checkbox], and [Radio] controls. @optionalTypeArgs mixin ToggleableStateMixin on TickerProviderStateMixin { /// Used by subclasses to manipulate the visual value of the control. @@ -94,6 +95,12 @@ mixin ToggleableStateMixin on TickerProviderStateMixin late CurvedAnimation _reactionFocusFade; late AnimationController _reactionFocusFadeController; + /// The amount of time a circular ink response should take to expand to its + /// full size if a radial reaction is drawn using + /// [ToggleablePainter.paintRadialReaction]. + Duration? get reactionAnimationDuration => _reactionAnimationDuration; + final Duration _reactionAnimationDuration = const Duration(milliseconds: 100); + /// Whether [value] of this control can be changed by user interaction. /// /// The control is considered interactive if the [onChanged] callback is @@ -149,7 +156,7 @@ mixin ToggleableStateMixin on TickerProviderStateMixin reverseCurve: Curves.easeOut, ); _reactionController = AnimationController( - duration: kRadialReactionDuration, + duration: _reactionAnimationDuration, vsync: this, ); _reaction = CurvedAnimation( @@ -275,31 +282,39 @@ mixin ToggleableStateMixin on TickerProviderStateMixin } } - /// Describes the current [MaterialState] of the Toggleable. + /// Describes the current [WidgetState] of the Toggleable. /// /// The returned set will include: /// - /// * [MaterialState.disabled], if [isInteractive] is false - /// * [MaterialState.hovered], if a pointer is hovering over the Toggleable - /// * [MaterialState.focused], if the Toggleable has input focus - /// * [MaterialState.selected], if [value] is true or null - Set get states => { - if (!isInteractive) MaterialState.disabled, - if (_hovering) MaterialState.hovered, - if (_focused) MaterialState.focused, - if (value ?? true) MaterialState.selected, + /// * [WidgetState.disabled], if [isInteractive] is false + /// * [WidgetState.hovered], if a pointer is hovering over the Toggleable + /// * [WidgetState.focused], if the Toggleable has input focus + /// * [WidgetState.selected], if [value] is true or null + Set get states => { + if (!isInteractive) WidgetState.disabled, + if (_hovering) WidgetState.hovered, + if (_focused) WidgetState.focused, + if (value ?? true) WidgetState.selected, }; /// Typically wraps a `painter` that draws the actual visuals of the /// Toggleable with logic to toggle it. /// - /// Consider providing a subclass of [ToggleablePainter] as a `painter`, which - /// implements logic to draw a radial ink reaction for this control. The - /// painter is usually configured with the [reaction], [position], - /// [reactionHoverFade], and [reactionFocusFade] animation provided by this - /// mixin. It is expected to draw the visuals of the Toggleable based on the - /// current value of these animations. The animations are triggered by - /// this mixin to transition the Toggleable from one state to another. + /// If drawing a radial ink reaction is desired (in Material Design for + /// example), consider providing a subclass of [ToggleablePainter] as a + /// `painter`, which implements logic to draw a radial ink reaction for this + /// control. The painter is usually configured with the [reaction], + /// [position], [reactionHoverFade], and [reactionFocusFade] animation + /// provided by this mixin. It is expected to draw the visuals of the + /// Toggleable based on the current value of these animations. The animations + /// are triggered by this mixin to transition the Toggleable from one state + /// to another. + /// + /// Material Toggleables must provide a [mouseCursor] which resolves to a + /// [MouseCursor] based on the current [WidgetState] of the Toggleable. + /// Cupertino Toggleables may not provide a [mouseCursor]. If no [mouseCursor] + /// is provided, [SystemMouseCursors.basic] will be used as the [mouseCursor] + /// across all [WidgetState]s. /// /// This method must be called from the [build] method of the [State] class /// that uses this mixin. The returned [Widget] must be returned from the @@ -308,7 +323,7 @@ mixin ToggleableStateMixin on TickerProviderStateMixin FocusNode? focusNode, ValueChanged? onFocusChange, bool autofocus = false, - required MaterialStateProperty mouseCursor, + WidgetStateProperty? mouseCursor, required Size size, required CustomPainter painter, }) { @@ -320,7 +335,7 @@ mixin ToggleableStateMixin on TickerProviderStateMixin enabled: isInteractive, onShowFocusHighlight: _handleFocusHighlightChanged, onShowHoverHighlight: _handleHoverChanged, - mouseCursor: mouseCursor.resolve(states), + mouseCursor: mouseCursor?.resolve(states) ?? SystemMouseCursors.basic, child: GestureDetector( excludeFromSemantics: !isInteractive, onTapDown: isInteractive ? _handleTapDown : null, @@ -344,8 +359,11 @@ mixin ToggleableStateMixin on TickerProviderStateMixin /// a Toggleable. /// /// Subclasses must implement the [paint] method to draw the actual visuals of -/// the Toggleable. In their [paint] method subclasses may call -/// [paintRadialReaction] to draw a radial ink reaction for this control. +/// the Toggleable. +/// +/// If drawing a radial ink reaction is desired (in Material +/// Design for example), subclasses may call [paintRadialReaction] in their +/// [paint] method. abstract class ToggleablePainter extends ChangeNotifier implements CustomPainter { /// The visual value of the control. /// @@ -541,6 +559,17 @@ abstract class ToggleablePainter extends ChangeNotifier implements CustomPainter notifyListeners(); } + /// Determines whether the toggleable shows as active. + bool get isActive => _isActive!; + bool? _isActive; + set isActive(bool? value) { + if (value == _isActive) { + return; + } + _isActive = value; + notifyListeners(); + } + /// Used by subclasses to paint the radial ink reaction for this control. /// /// The reaction is painted on the given canvas at the given offset. The @@ -575,7 +604,6 @@ abstract class ToggleablePainter extends ChangeNotifier implements CustomPainter } } - @override void dispose() { _position?.removeListener(notifyListeners); diff --git a/packages/flutter/lib/widgets.dart b/packages/flutter/lib/widgets.dart index 41eb3e9a77..a4b323a4ae 100644 --- a/packages/flutter/lib/widgets.dart +++ b/packages/flutter/lib/widgets.dart @@ -151,6 +151,7 @@ export 'src/widgets/text_selection_toolbar_layout_delegate.dart'; export 'src/widgets/texture.dart'; export 'src/widgets/ticker_provider.dart'; export 'src/widgets/title.dart'; +export 'src/widgets/toggleable.dart'; export 'src/widgets/transitions.dart'; export 'src/widgets/tween_animation_builder.dart'; export 'src/widgets/two_dimensional_scroll_view.dart'; diff --git a/packages/flutter/test/widgets/toggleable_test.dart b/packages/flutter/test/widgets/toggleable_test.dart new file mode 100644 index 0000000000..0c4627c3e9 --- /dev/null +++ b/packages/flutter/test/widgets/toggleable_test.dart @@ -0,0 +1,19 @@ +// 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() { + testWidgets('Toggleable exists in widget layer', (WidgetTester tester) async { + final TestPainter testPainter = TestPainter(); + expect(testPainter, isA()); + expect(testPainter, isNot(throwsException)); + }); +} + +class TestPainter extends ToggleablePainter { + @override + void paint(Canvas canvas, Size size) {} +}