From d8783ff4c2d517ee451607242adb167bf6892810 Mon Sep 17 00:00:00 2001 From: Hans Muller Date: Fri, 10 Jun 2022 08:12:49 -0700 Subject: [PATCH] Reland Added MaterialStatesController, updated InkWell et al. #103167 (#105656) --- .../material/text_button/text_button.1.dart | 102 ++++++++++ .../text_button/text_button.1_test.dart | 51 +++++ .../lib/src/material/button_style_button.dart | 112 ++++++----- .../lib/src/material/elevated_button.dart | 1 + .../flutter/lib/src/material/ink_well.dart | 180 ++++++++++++------ .../lib/src/material/material_state.dart | 23 +++ .../lib/src/material/outlined_button.dart | 1 + .../flutter/lib/src/material/text_button.dart | 8 + .../test/material/elevated_button_test.dart | 115 +++++++++++ .../flutter/test/material/ink_well_test.dart | 43 +++++ .../material_states_controller_test.dart | 85 +++++++++ .../test/material/outlined_button_test.dart | 117 ++++++++++++ .../test/material/text_button_test.dart | 118 +++++++++++- 13 files changed, 850 insertions(+), 106 deletions(-) create mode 100644 examples/api/lib/material/text_button/text_button.1.dart create mode 100644 examples/api/test/material/text_button/text_button.1_test.dart create mode 100644 packages/flutter/test/material/material_states_controller_test.dart diff --git a/examples/api/lib/material/text_button/text_button.1.dart b/examples/api/lib/material/text_button/text_button.1.dart new file mode 100644 index 0000000000..aa10c5a12a --- /dev/null +++ b/examples/api/lib/material/text_button/text_button.1.dart @@ -0,0 +1,102 @@ +// 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'; + +void main() { + runApp(const MaterialApp(home: Home())); +} + +class SelectableButton extends StatefulWidget { + const SelectableButton({ + super.key, + required this.selected, + this.style, + required this.onPressed, + required this.child, + }); + + final bool selected; + final ButtonStyle? style; + final VoidCallback? onPressed; + final Widget child; + + @override + State createState() => _SelectableButtonState(); + +} + +class _SelectableButtonState extends State { + late final MaterialStatesController statesController; + + @override + void initState() { + super.initState(); + statesController = MaterialStatesController({ + if (widget.selected) MaterialState.selected + }); + } + + @override + void didUpdateWidget(SelectableButton oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.selected != oldWidget.selected) { + statesController.update(MaterialState.selected, widget.selected); + } + } + + @override + Widget build(BuildContext context) { + return TextButton( + statesController: statesController, + style: widget.style, + onPressed: widget.onPressed, + child: widget.child, + ); + } +} + +class Home extends StatefulWidget { + const Home({ super.key }); + + @override + State createState() => _HomeState(); +} + +class _HomeState extends State { + bool selected = false; + + @override + Widget build(BuildContext context) { + return Scaffold( + body: Center( + child: SelectableButton( + selected: selected, + style: ButtonStyle( + foregroundColor: MaterialStateProperty.resolveWith( + (Set states) { + if (states.contains(MaterialState.selected)) { + return Colors.white; + } + return null; // defer to the defaults + }, + ), + backgroundColor: MaterialStateProperty.resolveWith( + (Set states) { + if (states.contains(MaterialState.selected)) { + return Colors.indigo; + } + return null; // defer to the defaults + }, + ), + ), + onPressed: () { + setState(() { selected = !selected; }); + }, + child: const Text('toggle selected'), + ), + ), + ); + } +} diff --git a/examples/api/test/material/text_button/text_button.1_test.dart b/examples/api/test/material/text_button/text_button.1_test.dart new file mode 100644 index 0000000000..795e090d03 --- /dev/null +++ b/examples/api/test/material/text_button/text_button.1_test.dart @@ -0,0 +1,51 @@ +// 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_api_samples/material/text_button/text_button.1.dart' as example; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + + testWidgets('SelectableButton', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + theme: ThemeData( + colorScheme: const ColorScheme.light(), + ), + home: const example.Home(), + ), + ); + + final Finder button = find.byType(example.SelectableButton); + + example.SelectableButton buttonWidget() => tester.widget(button); + + Material buttonMaterial() { + return tester.widget( + find.descendant( + of: find.byType(example.SelectableButton), + matching: find.byType(Material), + ), + ); + } + + expect(buttonWidget().selected, false); + expect(buttonMaterial().textStyle!.color, const ColorScheme.light().primary); // default button foreground color + expect(buttonMaterial().color, Colors.transparent); // default button background color + + await tester.tap(button); // Toggles the button's selected property. + await tester.pumpAndSettle(); + expect(buttonWidget().selected, true); + expect(buttonMaterial().textStyle!.color, Colors.white); + expect(buttonMaterial().color, Colors.indigo); + + + await tester.tap(button); // Toggles the button's selected property. + await tester.pumpAndSettle(); + expect(buttonWidget().selected, false); + expect(buttonMaterial().textStyle!.color, const ColorScheme.light().primary); + expect(buttonMaterial().color, Colors.transparent); + }); +} diff --git a/packages/flutter/lib/src/material/button_style_button.dart b/packages/flutter/lib/src/material/button_style_button.dart index 1ed4bffdde..3a22b198d0 100644 --- a/packages/flutter/lib/src/material/button_style_button.dart +++ b/packages/flutter/lib/src/material/button_style_button.dart @@ -14,7 +14,6 @@ import 'constants.dart'; import 'ink_well.dart'; import 'material.dart'; import 'material_state.dart'; -import 'material_state_mixin.dart'; import 'theme_data.dart'; /// The base [StatefulWidget] class for buttons whose style is defined by a [ButtonStyle] object. @@ -39,6 +38,7 @@ abstract class ButtonStyleButton extends StatefulWidget { required this.focusNode, required this.autofocus, required this.clipBehavior, + this.statesController, required this.child, }) : assert(autofocus != null), assert(clipBehavior != null); @@ -95,6 +95,9 @@ abstract class ButtonStyleButton extends StatefulWidget { /// {@macro flutter.widgets.Focus.autofocus} final bool autofocus; + /// {@macro flutter.material.inkwell.statesController} + final MaterialStatesController? statesController; + /// Typically the button's label. final Widget? child; @@ -191,34 +194,59 @@ abstract class ButtonStyleButton extends StatefulWidget { /// * [TextButton], a simple button without a shadow. /// * [ElevatedButton], a filled button whose material elevates when pressed. /// * [OutlinedButton], similar to [TextButton], but with an outline. -class _ButtonStyleState extends State with MaterialStateMixin, TickerProviderStateMixin { - AnimationController? _controller; - double? _elevation; - Color? _backgroundColor; +class _ButtonStyleState extends State with TickerProviderStateMixin { + AnimationController? controller; + double? elevation; + Color? backgroundColor; + MaterialStatesController? internalStatesController; + + void handleStatesControllerChange() { + // Force a rebuild to resolve MaterialStateProperty properties + setState(() { }); + } + + MaterialStatesController get statesController => widget.statesController ?? internalStatesController!; + + void initStatesController() { + if (widget.statesController == null) { + internalStatesController = MaterialStatesController(); + } + statesController.update(MaterialState.disabled, !widget.enabled); + statesController.addListener(handleStatesControllerChange); + } @override void initState() { super.initState(); - setMaterialState(MaterialState.disabled, !widget.enabled); - } - - @override - void dispose() { - _controller?.dispose(); - super.dispose(); + initStatesController(); } @override void didUpdateWidget(ButtonStyleButton oldWidget) { super.didUpdateWidget(oldWidget); - setMaterialState(MaterialState.disabled, !widget.enabled); - // If the button is disabled while a press gesture is currently ongoing, - // InkWell makes a call to handleHighlightChanged. This causes an exception - // because it calls setState in the middle of a build. To preempt this, we - // manually update pressed to false when this situation occurs. - if (isDisabled && isPressed) { - removeMaterialState(MaterialState.pressed); + if (widget.statesController != oldWidget.statesController) { + oldWidget.statesController?.removeListener(handleStatesControllerChange); + if (widget.statesController != null) { + internalStatesController?.dispose(); + internalStatesController = null; + } + initStatesController(); } + if (widget.enabled != oldWidget.enabled) { + statesController.update(MaterialState.disabled, !widget.enabled); + if (!widget.enabled) { + // The button may have been disabled while a press gesture is currently underway. + statesController.update(MaterialState.pressed, false); + } + } + } + + @override + void dispose() { + statesController.removeListener(handleStatesControllerChange); + internalStatesController?.dispose(); + controller?.dispose(); + super.dispose(); } @override @@ -237,7 +265,9 @@ class _ButtonStyleState extends State with MaterialStateMixin T? resolve(MaterialStateProperty? Function(ButtonStyle? style) getProperty) { return effectiveValue( - (ButtonStyle? style) => getProperty(style)?.resolve(materialStates), + (ButtonStyle? style) { + return getProperty(style)?.resolve(statesController.value); + }, ); } @@ -254,7 +284,7 @@ class _ButtonStyleState extends State with MaterialStateMixin final BorderSide? resolvedSide = resolve((ButtonStyle? style) => style?.side); final OutlinedBorder? resolvedShape = resolve((ButtonStyle? style) => style?.shape); - final MaterialStateMouseCursor resolvedMouseCursor = _MouseCursor( + final MaterialStateMouseCursor mouseCursor = _MouseCursor( (Set states) => effectiveValue((ButtonStyle? style) => style?.mouseCursor?.resolve(states)), ); @@ -309,16 +339,16 @@ class _ButtonStyleState extends State with MaterialStateMixin // 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 + && 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( + if (controller?.duration != resolvedAnimationDuration) { + controller?.dispose(); + controller = AnimationController( duration: resolvedAnimationDuration, vsync: this, ) @@ -328,12 +358,12 @@ class _ButtonStyleState extends State with MaterialStateMixin } }); } - resolvedBackgroundColor = _backgroundColor; // Defer changing the background color. - _controller!.value = 0; - _controller!.forward(); + resolvedBackgroundColor = backgroundColor; // Defer changing the background color. + controller!.value = 0; + controller!.forward(); } - _elevation = resolvedElevation; - _backgroundColor = resolvedBackgroundColor; + elevation = resolvedElevation; + backgroundColor = resolvedBackgroundColor; final Widget result = ConstrainedBox( constraints: effectiveConstraints, @@ -350,24 +380,18 @@ class _ButtonStyleState extends State with MaterialStateMixin child: InkWell( onTap: widget.onPressed, onLongPress: widget.onLongPress, - onHighlightChanged: updateMaterialState(MaterialState.pressed), - onHover: updateMaterialState( - MaterialState.hovered, - onChanged: widget.onHover, - ), - mouseCursor: resolvedMouseCursor, + onHover: widget.onHover, + mouseCursor: mouseCursor, enableFeedback: resolvedEnableFeedback, focusNode: widget.focusNode, canRequestFocus: widget.enabled, - onFocusChange: updateMaterialState( - MaterialState.focused, - onChanged: widget.onFocusChange, - ), + 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: resolvedForegroundColor), child: Padding( diff --git a/packages/flutter/lib/src/material/elevated_button.dart b/packages/flutter/lib/src/material/elevated_button.dart index 6d9708b7bb..0a4cb0d9e1 100644 --- a/packages/flutter/lib/src/material/elevated_button.dart +++ b/packages/flutter/lib/src/material/elevated_button.dart @@ -72,6 +72,7 @@ class ElevatedButton extends ButtonStyleButton { super.focusNode, super.autofocus = false, super.clipBehavior = Clip.none, + super.statesController, required super.child, }); diff --git a/packages/flutter/lib/src/material/ink_well.dart b/packages/flutter/lib/src/material/ink_well.dart index 87ff2f8e0f..29dfe58d5b 100644 --- a/packages/flutter/lib/src/material/ink_well.dart +++ b/packages/flutter/lib/src/material/ink_well.dart @@ -319,6 +319,7 @@ class InkResponse extends StatelessWidget { this.canRequestFocus = true, this.onFocusChange, this.autofocus = false, + this.statesController, }) : assert(containedInkWell != null), assert(highlightShape != null), assert(enableFeedback != null), @@ -581,6 +582,19 @@ class InkResponse extends StatelessWidget { /// slightly more efficient). RectCallback? getRectCallback(RenderBox referenceBox) => null; + /// {@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]. + /// + /// 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] + /// however, this may only be done when it's safe to call + /// [State.setState], like in an event handler. + /// {@endtemplate} + final MaterialStatesController? statesController; + @override Widget build(BuildContext context) { final _ParentInkResponseState? parentState = _ParentInkResponseProvider.of(context); @@ -614,6 +628,7 @@ class InkResponse extends StatelessWidget { parentState: parentState, getRectCallback: getRectCallback, debugCheckContext: debugCheckContext, + statesController: statesController, child: child, ); } @@ -665,6 +680,7 @@ class _InkResponseStateWidget extends StatefulWidget { this.parentState, this.getRectCallback, required this.debugCheckContext, + this.statesController, }) : assert(containedInkWell != null), assert(highlightShape != null), assert(enableFeedback != null), @@ -702,6 +718,7 @@ class _InkResponseStateWidget extends StatefulWidget { final _ParentInkResponseState? parentState; final _GetRectCallback? getRectCallback; final _CheckContext debugCheckContext; + final MaterialStatesController? statesController; @override _InkResponseState createState() => _InkResponseState(); @@ -738,16 +755,18 @@ enum _HighlightType { } class _InkResponseState extends State<_InkResponseStateWidget> - with AutomaticKeepAliveClientMixin<_InkResponseStateWidget> - implements _ParentInkResponseState { + with AutomaticKeepAliveClientMixin<_InkResponseStateWidget> + implements _ParentInkResponseState +{ Set? _splashes; InteractiveInkFeature? _currentSplash; bool _hovering = false; final Map<_HighlightType, InkHighlight?> _highlights = <_HighlightType, InkHighlight?>{}; late final Map> _actionMap = >{ - ActivateIntent: CallbackAction(onInvoke: _simulateTap), - ButtonActivateIntent: CallbackAction(onInvoke: _simulateTap), + ActivateIntent: CallbackAction(onInvoke: simulateTap), + ButtonActivateIntent: CallbackAction(onInvoke: simulateTap), }; + MaterialStatesController? internalStatesController; bool get highlightsExist => _highlights.values.where((InkHighlight? highlight) => highlight != null).isNotEmpty; @@ -769,38 +788,65 @@ class _InkResponseState extends State<_InkResponseStateWidget> } bool get _anyChildInkResponsePressed => _activeChildren.isNotEmpty; - void _simulateTap([Intent? intent]) { + void simulateTap([Intent? intent]) { _startNewSplash(context: context); - _handleTap(); + handleTap(); } - void _simulateLongPress() { + void simulateLongPress() { _startNewSplash(context: context); - _handleLongPress(); + handleLongPress(); + } + + void handleStatesControllerChange() { + // Force a rebuild to resolve widget.overlayColor, widget.mouseCursor + setState(() { }); + } + + MaterialStatesController get statesController => widget.statesController ?? internalStatesController!; + + void initStatesController() { + if (widget.statesController == null) { + internalStatesController = MaterialStatesController(); + } + statesController.update(MaterialState.disabled, !enabled); + statesController.addListener(handleStatesControllerChange); } @override void initState() { super.initState(); - FocusManager.instance.addHighlightModeListener(_handleFocusHighlightModeChange); + initStatesController(); + FocusManager.instance.addHighlightModeListener(handleFocusHighlightModeChange); } @override void didUpdateWidget(_InkResponseStateWidget oldWidget) { super.didUpdateWidget(oldWidget); - if (_isWidgetEnabled(widget) != _isWidgetEnabled(oldWidget)) { - if (enabled) { - // Don't call widget.onHover because many widgets, including the button - // widgets, apply setState to an ancestor context from onHover. - updateHighlight(_HighlightType.hover, value: _hovering, callOnHover: false); + if (widget.statesController != oldWidget.statesController) { + oldWidget.statesController?.removeListener(handleStatesControllerChange); + if (widget.statesController != null) { + internalStatesController?.dispose(); + internalStatesController = null; } - _updateFocusHighlights(); + initStatesController(); } + if (enabled != isWidgetEnabled(oldWidget)) { + statesController.update(MaterialState.disabled, !enabled); + if (!enabled) { + statesController.update(MaterialState.pressed, false); + } + // Don't call widget.onHover because many widgets, including the button + // widgets, apply setState to an ancestor context from onHover. + updateHighlight(_HighlightType.hover, value: _hovering, callOnHover: false); + } + updateFocusHighlights(); } @override void dispose() { - FocusManager.instance.removeHighlightModeListener(_handleFocusHighlightModeChange); + FocusManager.instance.removeHighlightModeListener(handleFocusHighlightModeChange); + statesController.removeListener(handleStatesControllerChange); super.dispose(); } @@ -808,21 +854,18 @@ class _InkResponseState extends State<_InkResponseStateWidget> bool get wantKeepAlive => highlightsExist || (_splashes != null && _splashes!.isNotEmpty); 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); + final Color? resolvedOverlayColor = widget.overlayColor?.resolve(statesController.value); 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; + return resolvedOverlayColor ?? widget.highlightColor ?? theme.highlightColor; case _HighlightType.focus: - return widget.overlayColor?.resolve(focused) ?? widget.focusColor ?? theme.focusColor; + return resolvedOverlayColor ?? widget.focusColor ?? theme.focusColor; case _HighlightType.hover: - return widget.overlayColor?.resolve(hovered) ?? widget.hoverColor ?? theme.hoverColor; + return resolvedOverlayColor ?? widget.hoverColor ?? theme.hoverColor; } } @@ -844,6 +887,20 @@ class _InkResponseState extends State<_InkResponseStateWidget> updateKeepAlive(); } + switch (type) { + case _HighlightType.pressed: + statesController.update(MaterialState.pressed, value); + break; + case _HighlightType.hover: + if (callOnHover) { + statesController.update(MaterialState.hovered, value); + } + break; + case _HighlightType.focus: + // see handleFocusUpdate() + break; + } + if (type == _HighlightType.pressed) { widget.parentState?.markChildInkResponsePressed(this, value); } @@ -893,8 +950,7 @@ class _InkResponseState extends State<_InkResponseStateWidget> final MaterialInkController inkController = Material.of(context)!; final RenderBox referenceBox = context.findRenderObject()! as RenderBox; final Offset position = referenceBox.globalToLocal(globalPosition); - const Set pressed = {MaterialState.pressed}; - final Color color = widget.overlayColor?.resolve(pressed) ?? widget.splashColor ?? Theme.of(context).splashColor; + 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; @@ -928,12 +984,12 @@ class _InkResponseState extends State<_InkResponseStateWidget> return splash; } - void _handleFocusHighlightModeChange(FocusHighlightMode mode) { + void handleFocusHighlightModeChange(FocusHighlightMode mode) { if (!mounted) { return; } setState(() { - _updateFocusHighlights(); + updateFocusHighlights(); }); } @@ -947,7 +1003,7 @@ class _InkResponseState extends State<_InkResponseStateWidget> } } - void _updateFocusHighlights() { + void updateFocusHighlights() { final bool showFocus; switch (FocusManager.instance.highlightMode) { case FocusHighlightMode.touch: @@ -961,13 +1017,18 @@ class _InkResponseState extends State<_InkResponseStateWidget> } bool _hasFocus = false; - void _handleFocusUpdate(bool hasFocus) { + void handleFocusUpdate(bool hasFocus) { _hasFocus = hasFocus; - _updateFocusHighlights(); + // Set here rather than updateHighlight because this widget's + // (MaterialState) states include MaterialState.focused if + // the InkWell _has_ the focus, rather than if it's showing + // the focus per FocusManager.instance.highlightMode. + statesController.update(MaterialState.focused, hasFocus); + updateFocusHighlights(); widget.onFocusChange?.call(hasFocus); } - void _handleTapDown(TapDownDetails details) { + void handleTapDown(TapDownDetails details) { if (_anyChildInkResponsePressed) { return; } @@ -975,7 +1036,7 @@ class _InkResponseState extends State<_InkResponseStateWidget> widget.onTapDown?.call(details); } - void _handleTapUp(TapUpDetails details) { + void handleTapUp(TapUpDetails details) { widget.onTapUp?.call(details); } @@ -990,6 +1051,7 @@ class _InkResponseState extends State<_InkResponseStateWidget> } else { globalPosition = details!.globalPosition; } + statesController.update(MaterialState.pressed, true); // ... before creating the splash final InteractiveInkFeature splash = _createInkFeature(globalPosition); _splashes ??= HashSet(); _splashes!.add(splash); @@ -999,7 +1061,7 @@ class _InkResponseState extends State<_InkResponseStateWidget> updateHighlight(_HighlightType.pressed, value: true); } - void _handleTap() { + void handleTap() { _currentSplash?.confirm(); _currentSplash = null; updateHighlight(_HighlightType.pressed, value: false); @@ -1011,21 +1073,21 @@ class _InkResponseState extends State<_InkResponseStateWidget> } } - void _handleTapCancel() { + void handleTapCancel() { _currentSplash?.cancel(); _currentSplash = null; widget.onTapCancel?.call(); updateHighlight(_HighlightType.pressed, value: false); } - void _handleDoubleTap() { + void handleDoubleTap() { _currentSplash?.confirm(); _currentSplash = null; updateHighlight(_HighlightType.pressed, value: false); widget.onDoubleTap?.call(); } - void _handleLongPress() { + void handleLongPress() { _currentSplash?.confirm(); _currentSplash = null; if (widget.onLongPress != null) { @@ -1055,27 +1117,27 @@ class _InkResponseState extends State<_InkResponseStateWidget> super.deactivate(); } - bool _isWidgetEnabled(_InkResponseStateWidget widget) { + bool isWidgetEnabled(_InkResponseStateWidget widget) { return widget.onTap != null || widget.onDoubleTap != null || widget.onLongPress != null || widget.onTapDown != null; } - bool get enabled => _isWidgetEnabled(widget); + bool get enabled => isWidgetEnabled(widget); - void _handleMouseEnter(PointerEnterEvent event) { + void handleMouseEnter(PointerEnterEvent event) { _hovering = true; if (enabled) { - _handleHoverChange(); + handleHoverChange(); } } - void _handleMouseExit(PointerExitEvent event) { + void handleMouseExit(PointerExitEvent event) { _hovering = false; // If the exit occurs after we've been disabled, we still // want to take down the highlights and run widget.onHover. - _handleHoverChange(); + handleHoverChange(); } - void _handleHoverChange() { + void handleHoverChange() { updateHighlight(_HighlightType.hover, value: _hovering); } @@ -1097,16 +1159,11 @@ class _InkResponseState extends State<_InkResponseStateWidget> _highlights[type]?.color = getHighlightColorForType(type); } - const Set pressed = {MaterialState.pressed}; - _currentSplash?.color = widget.overlayColor?.resolve(pressed) ?? 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, - { - if (!enabled) MaterialState.disabled, - if (_hovering && enabled) MaterialState.hovered, - if (_hasFocus) MaterialState.focused, - }, + statesController.value, ); return _ParentInkResponseProvider( @@ -1116,22 +1173,22 @@ class _InkResponseState extends State<_InkResponseStateWidget> child: Focus( focusNode: widget.focusNode, canRequestFocus: _canRequestFocus, - onFocusChange: _handleFocusUpdate, + onFocusChange: handleFocusUpdate, autofocus: widget.autofocus, child: MouseRegion( cursor: effectiveMouseCursor, - onEnter: _handleMouseEnter, - onExit: _handleMouseExit, + onEnter: handleMouseEnter, + onExit: handleMouseExit, child: Semantics( - onTap: widget.excludeFromSemantics || widget.onTap == null ? null : _simulateTap, - onLongPress: widget.excludeFromSemantics || widget.onLongPress == null ? null : _simulateLongPress, + onTap: widget.excludeFromSemantics || widget.onTap == null ? null : simulateTap, + onLongPress: widget.excludeFromSemantics || widget.onLongPress == null ? null : simulateLongPress, child: GestureDetector( - onTapDown: enabled ? _handleTapDown : null, - onTapUp: enabled ? _handleTapUp : null, - onTap: enabled ? _handleTap : null, - onTapCancel: enabled ? _handleTapCancel : null, - onDoubleTap: widget.onDoubleTap != null ? _handleDoubleTap : null, - onLongPress: widget.onLongPress != null ? _handleLongPress : null, + onTapDown: enabled ? handleTapDown : null, + onTapUp: enabled ? handleTapUp : null, + onTap: enabled ? handleTap : null, + onTapCancel: enabled ? handleTapCancel : null, + onDoubleTap: widget.onDoubleTap != null ? handleDoubleTap : null, + onLongPress: widget.onLongPress != null ? handleLongPress : null, behavior: HitTestBehavior.opaque, excludeFromSemantics: true, child: widget.child, @@ -1256,6 +1313,7 @@ class InkWell extends InkResponse { super.canRequestFocus, super.onFocusChange, super.autofocus, + super.statesController, }) : super( containedInkWell: true, highlightShape: BoxShape.rectangle, diff --git a/packages/flutter/lib/src/material/material_state.dart b/packages/flutter/lib/src/material/material_state.dart index 2566c50b33..503cd574e9 100644 --- a/packages/flutter/lib/src/material/material_state.dart +++ b/packages/flutter/lib/src/material/material_state.dart @@ -716,3 +716,26 @@ class MaterialStatePropertyAll implements MaterialStateProperty { @override String toString() => 'MaterialStatePropertyAll($value)'; } + +/// Manages a set of [MaterialState]s and notifies listeners of changes. +/// +/// Used by widgets that expose their internal state for the sake of +/// extensions that add support for additional states. See +/// [TextButton.statesController] for example. +/// +/// The controller's [value] is its current set of states. Listeners +/// are notified whenever the [value] changes. The [value] should only be +/// changed with [update]; it should not be modified directly. +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(); + } + } +} diff --git a/packages/flutter/lib/src/material/outlined_button.dart b/packages/flutter/lib/src/material/outlined_button.dart index 6c2669fb2a..790a3fd1b8 100644 --- a/packages/flutter/lib/src/material/outlined_button.dart +++ b/packages/flutter/lib/src/material/outlined_button.dart @@ -77,6 +77,7 @@ class OutlinedButton extends ButtonStyleButton { super.focusNode, super.autofocus = false, super.clipBehavior = Clip.none, + super.statesController, required Widget super.child, }); diff --git a/packages/flutter/lib/src/material/text_button.dart b/packages/flutter/lib/src/material/text_button.dart index 689155f5e4..bfa9bf9eb2 100644 --- a/packages/flutter/lib/src/material/text_button.dart +++ b/packages/flutter/lib/src/material/text_button.dart @@ -57,6 +57,13 @@ import 'theme_data.dart'; /// ** 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]. +/// +/// ** See code in examples/api/lib/material/text_button/text_button.1.dart ** +/// {@end-tool} +/// /// See also: /// /// * [OutlinedButton], a [TextButton] with a border outline. @@ -77,6 +84,7 @@ class TextButton extends ButtonStyleButton { super.focusNode, super.autofocus = false, super.clipBehavior = Clip.none, + super.statesController, required Widget super.child, }); diff --git a/packages/flutter/test/material/elevated_button_test.dart b/packages/flutter/test/material/elevated_button_test.dart index f7bc03541e..6a1d6ce022 100644 --- a/packages/flutter/test/material/elevated_button_test.dart +++ b/packages/flutter/test/material/elevated_button_test.dart @@ -1599,6 +1599,121 @@ void main() { ), ); }); + + testWidgets('ElevatedButton statesController', (WidgetTester tester) async { + int count = 0; + void valueChanged() { + count += 1; + } + final MaterialStatesController controller = MaterialStatesController(); + controller.addListener(valueChanged); + + await tester.pumpWidget( + MaterialApp( + home: Center( + child: ElevatedButton( + statesController: controller, + onPressed: () { }, + child: const Text('button'), + ), + ), + ), + ); + + expect(controller.value, {}); + expect(count, 0); + + final Offset center = tester.getCenter(find.byType(ElevatedButton)); + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + ); + await gesture.addPointer(); + await gesture.moveTo(center); + await tester.pumpAndSettle(); + + expect(controller.value, {MaterialState.hovered}); + expect(count, 1); + + await gesture.moveTo(Offset.zero); + await tester.pumpAndSettle(); + + expect(controller.value, {}); + expect(count, 2); + + await gesture.moveTo(center); + await tester.pumpAndSettle(); + + expect(controller.value, {MaterialState.hovered}); + expect(count, 3); + + await gesture.down(center); + await tester.pumpAndSettle(); + + expect(controller.value, {MaterialState.hovered, MaterialState.pressed}); + expect(count, 4); + + await gesture.up(); + await tester.pumpAndSettle(); + + expect(controller.value, {MaterialState.hovered}); + expect(count, 5); + + await gesture.moveTo(Offset.zero); + await tester.pumpAndSettle(); + + expect(controller.value, {}); + expect(count, 6); + + await gesture.down(center); + await tester.pumpAndSettle(); + expect(controller.value, {MaterialState.hovered, MaterialState.pressed}); + expect(count, 8); // adds hovered and pressed - two changes + + // If the button is rebuilt disabled, then the pressed state is + // removed. + await tester.pumpWidget( + MaterialApp( + home: Center( + child: ElevatedButton( + statesController: controller, + onPressed: null, + child: const Text('button'), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(controller.value, {MaterialState.hovered, MaterialState.disabled}); + expect(count, 10); // removes pressed and adds disabled - two changes + await gesture.moveTo(Offset.zero); + await tester.pumpAndSettle(); + expect(controller.value, {MaterialState.disabled}); + expect(count, 11); + await gesture.removePointer(); + }); + + testWidgets('Disabled ElevatedButton statesController', (WidgetTester tester) async { + int count = 0; + void valueChanged() { + count += 1; + } + final MaterialStatesController controller = MaterialStatesController(); + controller.addListener(valueChanged); + await tester.pumpWidget( + MaterialApp( + home: Center( + child: ElevatedButton( + statesController: controller, + onPressed: null, + child: const Text('button'), + ), + ), + ), + ); + expect(controller.value, {MaterialState.disabled}); + expect(count, 1); + }); + } TextStyle _iconStyle(WidgetTester tester, IconData icon) { diff --git a/packages/flutter/test/material/ink_well_test.dart b/packages/flutter/test/material/ink_well_test.dart index 13d76d2ea0..a9db62f105 100644 --- a/packages/flutter/test/material/ink_well_test.dart +++ b/packages/flutter/test/material/ink_well_test.dart @@ -1513,4 +1513,47 @@ void main() { final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paintsExactlyCountTimes(#drawCircle, 0)); }); + + testWidgets('InkWell dispose statesController', (WidgetTester tester) async { + int tapCount = 0; + Widget buildFrame(MaterialStatesController? statesController) { + return MaterialApp( + home: Scaffold( + body: Center( + child: InkWell( + statesController: statesController, + onTap: () { tapCount += 1; }, + child: const Text('inkwell'), + ), + ), + ), + ); + } + + final MaterialStatesController controller = MaterialStatesController(); + int pressedCount = 0; + controller.addListener(() { + if (controller.value.contains(MaterialState.pressed)) { + pressedCount += 1; + } + }); + + await tester.pumpWidget(buildFrame(controller)); + await tester.tap(find.byType(InkWell)); + await tester.pumpAndSettle(); + expect(tapCount, 1); + expect(pressedCount, 1); + + await tester.pumpWidget(buildFrame(null)); + await tester.tap(find.byType(InkWell)); + await tester.pumpAndSettle(); + expect(tapCount, 2); + expect(pressedCount, 1); + + await tester.pumpWidget(buildFrame(controller)); + await tester.tap(find.byType(InkWell)); + await tester.pumpAndSettle(); + expect(tapCount, 3); + expect(pressedCount, 2); + }); } diff --git a/packages/flutter/test/material/material_states_controller_test.dart b/packages/flutter/test/material/material_states_controller_test.dart new file mode 100644 index 0000000000..3449e975b6 --- /dev/null +++ b/packages/flutter/test/material/material_states_controller_test.dart @@ -0,0 +1,85 @@ +// 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() { + test('MaterialStatesController constructor', () { + expect(MaterialStatesController().value, {}); + expect(MaterialStatesController({}).value, {}); + expect(MaterialStatesController({MaterialState.selected}).value, {MaterialState.selected}); + }); + + test('MaterialStatesController update, listener', () { + int count = 0; + void valueChanged() { + count += 1; + } + final MaterialStatesController controller = MaterialStatesController(); + controller.addListener(valueChanged); + + controller.update(MaterialState.selected, true); + expect(controller.value, {MaterialState.selected}); + expect(count, 1); + controller.update(MaterialState.selected, true); + expect(controller.value, {MaterialState.selected}); + expect(count, 1); + + controller.update(MaterialState.hovered, false); + expect(count, 1); + expect(controller.value, {MaterialState.selected}); + controller.update(MaterialState.selected, false); + expect(count, 2); + expect(controller.value, {}); + + controller.update(MaterialState.hovered, true); + expect(controller.value, {MaterialState.hovered}); + expect(count, 3); + controller.update(MaterialState.hovered, true); + expect(controller.value, {MaterialState.hovered}); + expect(count, 3); + controller.update(MaterialState.pressed, true); + expect(controller.value, {MaterialState.hovered, MaterialState.pressed}); + expect(count, 4); + controller.update(MaterialState.selected, true); + expect(controller.value, {MaterialState.hovered, MaterialState.pressed, MaterialState.selected}); + expect(count, 5); + controller.update(MaterialState.selected, false); + expect(controller.value, {MaterialState.hovered, MaterialState.pressed}); + expect(count, 6); + controller.update(MaterialState.selected, false); + expect(controller.value, {MaterialState.hovered, MaterialState.pressed}); + expect(count, 6); + controller.update(MaterialState.pressed, false); + expect(controller.value, {MaterialState.hovered}); + expect(count, 7); + controller.update(MaterialState.hovered, false); + expect(controller.value, {}); + expect(count, 8); + + controller.removeListener(valueChanged); + controller.update(MaterialState.selected, true); + expect(controller.value, {MaterialState.selected}); + expect(count, 8); + }); + + + test('MaterialStatesController const initial value', () { + int count = 0; + void valueChanged() { + count += 1; + } + final MaterialStatesController controller = MaterialStatesController(const {MaterialState.selected}); + controller.addListener(valueChanged); + + controller.update(MaterialState.selected, true); + expect(controller.value, {MaterialState.selected}); + expect(count, 0); + + controller.update(MaterialState.selected, false); + expect(controller.value, {}); + expect(count, 1); + }); +} diff --git a/packages/flutter/test/material/outlined_button_test.dart b/packages/flutter/test/material/outlined_button_test.dart index 4f1b2a34db..b1a78e0195 100644 --- a/packages/flutter/test/material/outlined_button_test.dart +++ b/packages/flutter/test/material/outlined_button_test.dart @@ -1717,6 +1717,123 @@ void main() { expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); }); + + testWidgets('OutlinedButton statesController', (WidgetTester tester) async { + int count = 0; + void valueChanged() { + count += 1; + } + final MaterialStatesController controller = MaterialStatesController(); + controller.addListener(valueChanged); + + await tester.pumpWidget( + MaterialApp( + home: Center( + child: OutlinedButton( + statesController: controller, + onPressed: () { }, + child: const Text('button'), + ), + ), + ), + ); + + expect(controller.value, {}); + expect(count, 0); + + final Offset center = tester.getCenter(find.byType(OutlinedButton)); + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + ); + await gesture.addPointer(); + await gesture.moveTo(center); + await tester.pumpAndSettle(); + + expect(controller.value, {MaterialState.hovered}); + expect(count, 1); + + await gesture.moveTo(Offset.zero); + await tester.pumpAndSettle(); + + expect(controller.value, {}); + expect(count, 2); + + await gesture.moveTo(center); + await tester.pumpAndSettle(); + + expect(controller.value, {MaterialState.hovered}); + expect(count, 3); + + await gesture.down(center); + await tester.pumpAndSettle(); + + expect(controller.value, {MaterialState.hovered, MaterialState.pressed}); + expect(count, 4); + + await gesture.up(); + await tester.pumpAndSettle(); + + expect(controller.value, {MaterialState.hovered}); + expect(count, 5); + + await gesture.moveTo(Offset.zero); + await tester.pumpAndSettle(); + + expect(controller.value, {}); + expect(count, 6); + + await gesture.down(center); + await tester.pumpAndSettle(); + expect(controller.value, {MaterialState.hovered, MaterialState.pressed}); + expect(count, 8); // adds hovered and pressed - two changes + + // If the button is rebuilt disabled, then the pressed state is + // removed. + await tester.pumpWidget( + MaterialApp( + home: Center( + child: OutlinedButton( + statesController: controller, + onPressed: null, + child: const Text('button'), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(controller.value, {MaterialState.hovered, MaterialState.disabled}); + expect(count, 10); // removes pressed and adds disabled - two changes + + await gesture.moveTo(Offset.zero); + await tester.pumpAndSettle(); + expect(controller.value, {MaterialState.disabled}); + expect(count, 11); + + await gesture.removePointer(); + }); + + testWidgets('Disabled OutlinedButton statesController', (WidgetTester tester) async { + int count = 0; + void valueChanged() { + count += 1; + } + final MaterialStatesController controller = MaterialStatesController(); + controller.addListener(valueChanged); + + await tester.pumpWidget( + MaterialApp( + home: Center( + child: OutlinedButton( + statesController: controller, + onPressed: null, + child: const Text('button'), + ), + ), + ), + ); + expect(controller.value, {MaterialState.disabled}); + expect(count, 1); + }); } TextStyle _iconStyle(WidgetTester tester, IconData icon) { diff --git a/packages/flutter/test/material/text_button_test.dart b/packages/flutter/test/material/text_button_test.dart index 36f3bf1b80..d950ad1733 100644 --- a/packages/flutter/test/material/text_button_test.dart +++ b/packages/flutter/test/material/text_button_test.dart @@ -441,7 +441,6 @@ void main() { ), ); - final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.byType(TextButton))); @@ -1525,6 +1524,123 @@ void main() { expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); }); + + testWidgets('TextButton statesController', (WidgetTester tester) async { + int count = 0; + void valueChanged() { + count += 1; + } + final MaterialStatesController controller = MaterialStatesController(); + controller.addListener(valueChanged); + + await tester.pumpWidget( + MaterialApp( + home: Center( + child: TextButton( + statesController: controller, + onPressed: () { }, + child: const Text('button'), + ), + ), + ), + ); + + expect(controller.value, {}); + expect(count, 0); + + final Offset center = tester.getCenter(find.byType(TextButton)); + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + ); + await gesture.addPointer(); + await gesture.moveTo(center); + await tester.pumpAndSettle(); + + expect(controller.value, {MaterialState.hovered}); + expect(count, 1); + + await gesture.moveTo(Offset.zero); + await tester.pumpAndSettle(); + + expect(controller.value, {}); + expect(count, 2); + + await gesture.moveTo(center); + await tester.pumpAndSettle(); + + expect(controller.value, {MaterialState.hovered}); + expect(count, 3); + + await gesture.down(center); + await tester.pumpAndSettle(); + + expect(controller.value, {MaterialState.hovered, MaterialState.pressed}); + expect(count, 4); + + await gesture.up(); + await tester.pumpAndSettle(); + + expect(controller.value, {MaterialState.hovered}); + expect(count, 5); + + await gesture.moveTo(Offset.zero); + await tester.pumpAndSettle(); + + expect(controller.value, {}); + expect(count, 6); + + await gesture.down(center); + await tester.pumpAndSettle(); + expect(controller.value, {MaterialState.hovered, MaterialState.pressed}); + expect(count, 8); // adds hovered and pressed - two changes + + // If the button is rebuilt disabled, then the pressed state is + // removed. + await tester.pumpWidget( + MaterialApp( + home: Center( + child: TextButton( + statesController: controller, + onPressed: null, + child: const Text('button'), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(controller.value, {MaterialState.hovered, MaterialState.disabled}); + expect(count, 10); // removes pressed and adds disabled - two changes + + await gesture.moveTo(Offset.zero); + await tester.pumpAndSettle(); + expect(controller.value, {MaterialState.disabled}); + expect(count, 11); + + await gesture.removePointer(); + }); + + testWidgets('Disabled TextButton statesController', (WidgetTester tester) async { + int count = 0; + void valueChanged() { + count += 1; + } + final MaterialStatesController controller = MaterialStatesController(); + controller.addListener(valueChanged); + + await tester.pumpWidget( + MaterialApp( + home: Center( + child: TextButton( + statesController: controller, + onPressed: null, + child: const Text('button'), + ), + ), + ), + ); + expect(controller.value, {MaterialState.disabled}); + expect(count, 1); + }); } TextStyle? _iconStyle(WidgetTester tester, IconData icon) {