diff --git a/packages/flutter/lib/src/material/checkbox.dart b/packages/flutter/lib/src/material/checkbox.dart index e394b76907..5f6e224971 100644 --- a/packages/flutter/lib/src/material/checkbox.dart +++ b/packages/flutter/lib/src/material/checkbox.dart @@ -159,7 +159,6 @@ class Checkbox extends StatefulWidget { class _CheckboxState extends State with TickerProviderStateMixin { bool get enabled => widget.onChanged != null; Map _actionMap; - bool _showHighlight = false; @override void initState() { @@ -168,8 +167,6 @@ class _CheckboxState extends State with TickerProviderStateMixin { SelectAction.key: _createAction, if (!kIsWeb) ActivateAction.key: _createAction, }; - _updateHighlightMode(FocusManager.instance.highlightMode); - FocusManager.instance.addHighlightModeListener(_handleFocusHighlightModeChange); } void _actionHandler(FocusNode node, Intent intent){ @@ -197,28 +194,20 @@ class _CheckboxState extends State with TickerProviderStateMixin { ); } - void _updateHighlightMode(FocusHighlightMode mode) { - switch (FocusManager.instance.highlightMode) { - case FocusHighlightMode.touch: - _showHighlight = false; - break; - case FocusHighlightMode.traditional: - _showHighlight = true; - break; + bool _focused = false; + void _handleFocusHighlightChanged(bool focused) { + if (focused != _focused) { + setState(() { _focused = focused; }); } } - void _handleFocusHighlightModeChange(FocusHighlightMode mode) { - if (!mounted) { - return; + bool _hovering = false; + void _handleHoverChanged(bool hovering) { + if (hovering != _hovering) { + setState(() { _hovering = hovering; }); } - setState(() { _updateHighlightMode(mode); }); } - bool hovering = false; - void _handleMouseEnter(PointerEnterEvent event) => setState(() { hovering = true; }); - void _handleMouseExit(PointerExitEvent event) => setState(() { hovering = false; }); - @override Widget build(BuildContext context) { assert(debugCheckHasMaterial(context)); @@ -233,35 +222,30 @@ class _CheckboxState extends State with TickerProviderStateMixin { break; } final BoxConstraints additionalConstraints = BoxConstraints.tight(size); - return MouseRegion( - onEnter: enabled ? _handleMouseEnter : null, - onExit: enabled ? _handleMouseExit : null, - child: Actions( - actions: _actionMap, - child: Focus( - focusNode: widget.focusNode, - autofocus: widget.autofocus, - canRequestFocus: enabled, - debugLabel: '${describeIdentity(widget)}(${widget.value})', - child: Builder( - builder: (BuildContext context) { - return _CheckboxRenderObjectWidget( - value: widget.value, - tristate: widget.tristate, - activeColor: widget.activeColor ?? themeData.toggleableActiveColor, - checkColor: widget.checkColor ?? const Color(0xFFFFFFFF), - inactiveColor: enabled ? themeData.unselectedWidgetColor : themeData.disabledColor, - focusColor: widget.focusColor ?? themeData.focusColor, - hoverColor: widget.hoverColor ?? themeData.hoverColor, - onChanged: widget.onChanged, - additionalConstraints: additionalConstraints, - vsync: this, - hasFocus: enabled && _showHighlight && Focus.of(context).hasFocus, - hovering: enabled && _showHighlight && hovering, - ); - }, - ), - ), + return FocusableActionDetector( + actions: _actionMap, + focusNode: widget.focusNode, + autofocus: widget.autofocus, + enabled: enabled, + onShowFocusHighlight: _handleFocusHighlightChanged, + onShowHoverHighlight: _handleHoverChanged, + child: Builder( + builder: (BuildContext context) { + return _CheckboxRenderObjectWidget( + value: widget.value, + tristate: widget.tristate, + activeColor: widget.activeColor ?? themeData.toggleableActiveColor, + checkColor: widget.checkColor ?? const Color(0xFFFFFFFF), + inactiveColor: enabled ? themeData.unselectedWidgetColor : themeData.disabledColor, + focusColor: widget.focusColor ?? themeData.focusColor, + hoverColor: widget.hoverColor ?? themeData.hoverColor, + onChanged: widget.onChanged, + additionalConstraints: additionalConstraints, + vsync: this, + hasFocus: _focused, + hovering: _hovering, + ); + }, ), ); } diff --git a/packages/flutter/lib/src/material/radio.dart b/packages/flutter/lib/src/material/radio.dart index a4c5970c0c..c8d90c825d 100644 --- a/packages/flutter/lib/src/material/radio.dart +++ b/packages/flutter/lib/src/material/radio.dart @@ -187,7 +187,6 @@ class Radio extends StatefulWidget { class _RadioState extends State> with TickerProviderStateMixin { bool get enabled => widget.onChanged != null; Map _actionMap; - bool _showHighlight = false; @override void initState() { @@ -196,8 +195,6 @@ class _RadioState extends State> with TickerProviderStateMixin { SelectAction.key: _createAction, if (!kIsWeb) ActivateAction.key: _createAction, }; - _updateHighlightMode(FocusManager.instance.highlightMode); - FocusManager.instance.addHighlightModeListener(_handleFocusHighlightModeChange); } void _actionHandler(FocusNode node, Intent intent){ @@ -215,28 +212,20 @@ class _RadioState extends State> with TickerProviderStateMixin { ); } - void _updateHighlightMode(FocusHighlightMode mode) { - switch (FocusManager.instance.highlightMode) { - case FocusHighlightMode.touch: - _showHighlight = false; - break; - case FocusHighlightMode.traditional: - _showHighlight = true; - break; + bool _focused = false; + void _handleHighlightChanged(bool focused) { + if (_focused != focused) { + setState(() { _focused = focused; }); } } - void _handleFocusHighlightModeChange(FocusHighlightMode mode) { - if (!mounted) { - return; + bool _hovering = false; + void _handleHoverChanged(bool hovering) { + if (_hovering != hovering) { + setState(() { _hovering = hovering; }); } - setState(() { _updateHighlightMode(mode); }); } - bool hovering = false; - void _handleMouseEnter(PointerEnterEvent event) => setState(() { hovering = true; }); - void _handleMouseExit(PointerExitEvent event) => setState(() { hovering = false; }); - Color _getInactiveColor(ThemeData themeData) { return enabled ? themeData.unselectedWidgetColor : themeData.disabledColor; } @@ -260,33 +249,28 @@ class _RadioState extends State> with TickerProviderStateMixin { break; } final BoxConstraints additionalConstraints = BoxConstraints.tight(size); - return MouseRegion( - onEnter: enabled ? _handleMouseEnter : null, - onExit: enabled ? _handleMouseExit : null, - child: Actions( - actions: _actionMap, - child: Focus( - focusNode: widget.focusNode, - autofocus: widget.autofocus, - canRequestFocus: enabled, - debugLabel: '${describeIdentity(widget)}(${widget.value})', - child: Builder( - builder: (BuildContext context) { - return _RadioRenderObjectWidget( - selected: widget.value == widget.groupValue, - activeColor: widget.activeColor ?? themeData.toggleableActiveColor, - inactiveColor: _getInactiveColor(themeData), - focusColor: widget.focusColor ?? themeData.focusColor, - hoverColor: widget.hoverColor ?? themeData.hoverColor, - onChanged: enabled ? _handleChanged : null, - additionalConstraints: additionalConstraints, - vsync: this, - hasFocus: enabled && _showHighlight && Focus.of(context).hasFocus, - hovering: enabled && _showHighlight && hovering, - ); - }, - ), - ), + return FocusableActionDetector( + actions: _actionMap, + focusNode: widget.focusNode, + autofocus: widget.autofocus, + enabled: enabled, + onShowFocusHighlight: _handleHighlightChanged, + onShowHoverHighlight: _handleHoverChanged, + child: Builder( + builder: (BuildContext context) { + return _RadioRenderObjectWidget( + selected: widget.value == widget.groupValue, + activeColor: widget.activeColor ?? themeData.toggleableActiveColor, + inactiveColor: _getInactiveColor(themeData), + focusColor: widget.focusColor ?? themeData.focusColor, + hoverColor: widget.hoverColor ?? themeData.hoverColor, + onChanged: enabled ? _handleChanged : null, + additionalConstraints: additionalConstraints, + vsync: this, + hasFocus: _focused, + hovering: _hovering, + ); + }, ), ); } diff --git a/packages/flutter/lib/src/material/switch.dart b/packages/flutter/lib/src/material/switch.dart index 435408e376..d4168d48e2 100644 --- a/packages/flutter/lib/src/material/switch.dart +++ b/packages/flutter/lib/src/material/switch.dart @@ -214,7 +214,6 @@ class Switch extends StatefulWidget { class _SwitchState extends State with TickerProviderStateMixin { Map _actionMap; - bool _showHighlight = false; @override void initState() { @@ -223,8 +222,6 @@ class _SwitchState extends State with TickerProviderStateMixin { SelectAction.key: _createAction, if (!kIsWeb) ActivateAction.key: _createAction, }; - _updateHighlightMode(FocusManager.instance.highlightMode); - FocusManager.instance.addHighlightModeListener(_handleFocusHighlightModeChange); } void _actionHandler(FocusNode node, Intent intent){ @@ -242,22 +239,18 @@ class _SwitchState extends State with TickerProviderStateMixin { ); } - void _updateHighlightMode(FocusHighlightMode mode) { - switch (FocusManager.instance.highlightMode) { - case FocusHighlightMode.touch: - _showHighlight = false; - break; - case FocusHighlightMode.traditional: - _showHighlight = true; - break; + bool _focused = false; + void _handleFocusHighlightChanged(bool focused) { + if (focused != _focused) { + setState(() { _focused = focused; }); } } - void _handleFocusHighlightModeChange(FocusHighlightMode mode) { - if (!mounted) { - return; + bool _hovering = false; + void _handleHoverChanged(bool hovering) { + if (hovering != _hovering) { + setState(() { _hovering = hovering; }); } - setState(() { _updateHighlightMode(mode); }); } Size getSwitchSize(ThemeData theme) { @@ -275,10 +268,6 @@ class _SwitchState extends State with TickerProviderStateMixin { bool get enabled => widget.onChanged != null; - bool hovering = false; - void _handleMouseEnter(PointerEnterEvent event) => setState(() { hovering = true; }); - void _handleMouseExit(PointerExitEvent event) => setState(() { hovering = false; }); - Widget buildMaterialSwitch(BuildContext context) { assert(debugCheckHasMaterial(context)); final ThemeData theme = Theme.of(context); @@ -300,40 +289,34 @@ class _SwitchState extends State with TickerProviderStateMixin { inactiveTrackColor = widget.inactiveTrackColor ?? (isDark ? Colors.white10 : Colors.black12); } - return MouseRegion( - onEnter: enabled ? _handleMouseEnter : null, - onExit: enabled ? _handleMouseExit : null, - child: Actions( - actions: _actionMap, - child: Focus( - focusNode: widget.focusNode, - autofocus: widget.autofocus, - canRequestFocus: enabled, - debugLabel: '${describeIdentity(widget)}({$widget.value})', - child: Builder( - builder: (BuildContext context) { - final bool hasFocus = Focus.of(context).hasFocus; - return _SwitchRenderObjectWidget( - dragStartBehavior: widget.dragStartBehavior, - value: widget.value, - activeColor: activeThumbColor, - inactiveColor: inactiveThumbColor, - hoverColor: hoverColor, - focusColor: focusColor, - activeThumbImage: widget.activeThumbImage, - inactiveThumbImage: widget.inactiveThumbImage, - activeTrackColor: activeTrackColor, - inactiveTrackColor: inactiveTrackColor, - configuration: createLocalImageConfiguration(context), - onChanged: widget.onChanged, - additionalConstraints: BoxConstraints.tight(getSwitchSize(theme)), - hasFocus: enabled && _showHighlight && hasFocus, - hovering: enabled && _showHighlight && hovering, - vsync: this, - ); - }, - ), - ), + return FocusableActionDetector( + actions: _actionMap, + focusNode: widget.focusNode, + autofocus: widget.autofocus, + enabled: enabled, + onShowFocusHighlight: _handleFocusHighlightChanged, + onShowHoverHighlight: _handleHoverChanged, + child: Builder( + builder: (BuildContext context) { + return _SwitchRenderObjectWidget( + dragStartBehavior: widget.dragStartBehavior, + value: widget.value, + activeColor: activeThumbColor, + inactiveColor: inactiveThumbColor, + hoverColor: hoverColor, + focusColor: focusColor, + activeThumbImage: widget.activeThumbImage, + inactiveThumbImage: widget.inactiveThumbImage, + activeTrackColor: activeTrackColor, + inactiveTrackColor: inactiveTrackColor, + configuration: createLocalImageConfiguration(context), + onChanged: widget.onChanged, + additionalConstraints: BoxConstraints.tight(getSwitchSize(theme)), + hasFocus: _focused, + hovering: _hovering, + vsync: this, + ); + }, ), ); } diff --git a/packages/flutter/lib/src/material/toggleable.dart b/packages/flutter/lib/src/material/toggleable.dart index 22b497bed4..8dd792204b 100644 --- a/packages/flutter/lib/src/material/toggleable.dart +++ b/packages/flutter/lib/src/material/toggleable.dart @@ -474,7 +474,9 @@ abstract class RenderToggleable extends RenderConstrainedBox { final double reactionRadius = hasFocus || hovering ? kRadialReactionRadius : _kRadialReactionRadiusTween.evaluate(_reaction); - canvas.drawCircle(center + offset, reactionRadius, reactionPaint); + if (reactionRadius > 0.0) { + canvas.drawCircle(center + offset, reactionRadius, reactionPaint); + } } } diff --git a/packages/flutter/lib/src/widgets/actions.dart b/packages/flutter/lib/src/widgets/actions.dart index a036aad109..8e7159926b 100644 --- a/packages/flutter/lib/src/widgets/actions.dart +++ b/packages/flutter/lib/src/widgets/actions.dart @@ -1,11 +1,16 @@ // Copyright 2019 The Chromium 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 'package:flutter/foundation.dart'; +import 'package:flutter/gestures.dart'; +import 'basic.dart'; import 'focus_manager.dart'; +import 'focus_scope.dart'; import 'framework.dart'; +import 'shortcuts.dart'; /// Creates actions for use in defining shortcuts. /// @@ -197,12 +202,14 @@ class Actions extends InheritedWidget { /// default-constructed [ActionDispatcher]. final ActionDispatcher dispatcher; + /// {@template flutter.widgets.actions.actions} /// A map of [Intent] keys to [ActionFactory] factory methods that defines /// which actions this widget knows about. /// /// For performance reasons, it is recommended that a pre-built map is /// passed in here (e.g. a final variable from your widget class) instead of /// defining it inline in the build function. + /// {@endtemplate} final Map actions; // Finds the nearest valid ActionDispatcher, or creates a new one if it @@ -355,6 +362,313 @@ class Actions extends InheritedWidget { } } +/// A widget that combines the functionality of [Actions], [Shortcuts], +/// [MouseRegion] and a [Focus] widget to create a detector that defines actions +/// and key bindings, and provides callbacks for handling focus and hover +/// highlights. +/// +/// This widget can be used to give a control the required detection modes for +/// focus and hover handling. It is most often used when authoring a new control +/// widget, and the new control should be enabled for keyboard traversal and +/// activation. +/// +/// {@tool snippet --template=stateful_widget_material} +/// This example shows how keyboard interaction can be added to a custom control +/// that changes color when hovered and focused, and can toggle a light when +/// activated, either by touch or by hitting the `X` key on the keyboard. +/// +/// This example defines its own key binding for the `X` key, but in this case, +/// there is also a default key binding for [ActivateAction] in the default key +/// bindings created by [WidgetsApp] (the parent for [MaterialApp], and +/// [CupertinoApp]), so the `ENTER` key will also activate the control. +/// +/// ```dart imports +/// import 'package:flutter/services.dart'; +/// ``` +/// +/// ```dart preamble +/// class FadButton extends StatefulWidget { +/// const FadButton({Key key, this.onPressed, this.child}) : super(key: key); +/// +/// final VoidCallback onPressed; +/// final Widget child; +/// +/// @override +/// _FadButtonState createState() => _FadButtonState(); +/// } +/// +/// class _FadButtonState extends State { +/// bool _focused = false; +/// bool _hovering = false; +/// bool _on = false; +/// Map _actionMap; +/// Map _shortcutMap; +/// +/// @override +/// void initState() { +/// super.initState(); +/// _actionMap = { +/// ActivateAction.key: () { +/// return CallbackAction( +/// ActivateAction.key, +/// onInvoke: (FocusNode node, Intent intent) => _toggleState(), +/// ); +/// }, +/// }; +/// _shortcutMap = { +/// LogicalKeySet(LogicalKeyboardKey.keyX): Intent(ActivateAction.key), +/// }; +/// } +/// +/// Color get color { +/// Color baseColor = Colors.lightBlue; +/// if (_focused) { +/// baseColor = Color.alphaBlend(Colors.black.withOpacity(0.25), baseColor); +/// } +/// if (_hovering) { +/// baseColor = Color.alphaBlend(Colors.black.withOpacity(0.1), baseColor); +/// } +/// return baseColor; +/// } +/// +/// void _toggleState() { +/// setState(() { +/// _on = !_on; +/// }); +/// } +/// +/// void _handleFocusHighlight(bool value) { +/// setState(() { +/// _focused = value; +/// }); +/// } +/// +/// void _handleHoveHighlight(bool value) { +/// setState(() { +/// _hovering = value; +/// }); +/// } +/// +/// @override +/// Widget build(BuildContext context) { +/// return GestureDetector( +/// onTap: _toggleState, +/// child: FocusableActionDetector( +/// actions: _actionMap, +/// shortcuts: _shortcutMap, +/// onShowFocusHighlight: _handleFocusHighlight, +/// onShowHoverHighlight: _handleHoveHighlight, +/// child: Row( +/// children: [ +/// Container( +/// padding: EdgeInsets.all(10.0), +/// color: color, +/// child: widget.child, +/// ), +/// Container( +/// width: 30, +/// height: 30, +/// margin: EdgeInsets.all(10.0), +/// color: _on ? Colors.red : Colors.transparent, +/// ), +/// ], +/// ), +/// ), +/// ); +/// } +/// } +/// ``` +/// +/// ```dart +/// Widget build(BuildContext context) { +/// return Scaffold( +/// appBar: AppBar( +/// title: Text('FocusableActionDetector Example'), +/// ), +/// body: Center( +/// child: Row( +/// mainAxisAlignment: MainAxisAlignment.center, +/// children: [ +/// Padding( +/// padding: const EdgeInsets.all(8.0), +/// child: FlatButton(onPressed: () {}, child: Text('Press Me')), +/// ), +/// Padding( +/// padding: const EdgeInsets.all(8.0), +/// child: FadButton(onPressed: () {}, child: Text('And Me')), +/// ), +/// ], +/// ), +/// ), +/// ); +/// } +/// ``` +/// {@end-tool} +/// +/// This widget doesn't have any visual representation, it is just a detector that +/// provides focus and hover capabilities. +/// +/// It hosts its own [FocusNode] or uses [focusNode], if given. +class FocusableActionDetector extends StatefulWidget { + /// Create a const [FocusableActionDetector]. + /// + /// The [enabled], [autofocus], and [child] arguments must not be null. + const FocusableActionDetector({ + Key key, + this.enabled = true, + this.focusNode, + this.autofocus = false, + this.shortcuts, + this.actions, + this.onShowFocusHighlight, + this.onShowHoverHighlight, + this.onFocusChange, + @required this.child, + }) : assert(enabled != null), + assert(autofocus != null), + assert(child != null), + super(key: key); + + /// Is this widget enabled or not. + /// + /// If disabled, will not send any notifications needed to update highlight or + /// focus state, and will not define or respond to any actions or shortcuts. + /// + /// When disabled, adds [Focus] to the widget tree, but sets + /// [Focus.canRequestFocus] to false. + final bool enabled; + + /// {@macro flutter.widgets.Focus.focusNode} + final FocusNode focusNode; + + /// {@macro flutter.widgets.Focus.autofocus} + final bool autofocus; + + /// {@macro flutter.widgets.actions.actions} + final Map actions; + + /// {@macro flutter.widgets.shortcuts.shortcuts} + final Map shortcuts; + + /// A function that will be called when the focus highlight should be shown or hidden. + final ValueChanged onShowFocusHighlight; + + /// A function that will be called when the hover highlight should be shown or hidden. + final ValueChanged onShowHoverHighlight; + + /// A function that will be called when the focus changes. + /// + /// Called with true if the [focusNode] has primary focus. + final ValueChanged onFocusChange; + + /// The child widget for this [FocusableActionDetector] widget. + /// + /// {@macro flutter.widgets.child} + final Widget child; + + @override + _FocusableActionDetectorState createState() => _FocusableActionDetectorState(); +} + +class _FocusableActionDetectorState extends State { + @override + void initState() { + super.initState(); + _updateHighlightMode(FocusManager.instance.highlightMode); + FocusManager.instance.addHighlightModeListener(_handleFocusHighlightModeChange); + } + + @override + void dispose() { + FocusManager.instance.removeHighlightModeListener(_handleFocusHighlightModeChange); + super.dispose(); + } + + bool _canShowHighlight = false; + void _updateHighlightMode(FocusHighlightMode mode) { + final bool couldShowHighlight = _canShowHighlight; + switch (FocusManager.instance.highlightMode) { + case FocusHighlightMode.touch: + _canShowHighlight = false; + break; + case FocusHighlightMode.traditional: + _canShowHighlight = true; + break; + } + if (couldShowHighlight != _canShowHighlight) { + _handleShowFocusHighlight(); + _handleShowHoverHighlight(); + } + } + + /// Have to have this separate from the _updateHighlightMode because it gets + /// called in initState, where things aren't mounted yet. + void _handleFocusHighlightModeChange(FocusHighlightMode mode) { + if (!mounted) { + return; + } + _updateHighlightMode(mode); + } + + bool _hovering = false; + void _handleMouseEnter(PointerEnterEvent event) { + assert(widget.onShowHoverHighlight != null); + if (!_hovering) { + // TODO(gspencergoog): remove scheduleMicrotask once MouseRegion event timing has changed. + scheduleMicrotask(() { setState(() { _hovering = true; _handleShowHoverHighlight(); }); }); + } + } + + void _handleMouseExit(PointerExitEvent event) { + assert(widget.onShowHoverHighlight != null); + if (_hovering) { + // TODO(gspencergoog): remove scheduleMicrotask once MouseRegion event timing has changed. + scheduleMicrotask(() { setState(() { _hovering = false; _handleShowHoverHighlight(); }); }); + } + } + + bool _focused = false; + void _handleFocusChange(bool focused) { + if (_focused != focused) { + setState(() { + _focused = focused; + _handleShowFocusHighlight(); + widget.onFocusChange?.call(_focused); + }); + } + } + + void _handleShowHoverHighlight() { + widget.onShowHoverHighlight?.call(_hovering && widget.enabled && _canShowHighlight); + } + + void _handleShowFocusHighlight() { + widget.onShowFocusHighlight?.call(_focused && widget.enabled && _canShowHighlight); + } + + @override + Widget build(BuildContext context) { + Widget child = MouseRegion( + onEnter: _handleMouseEnter, + onExit: _handleMouseExit, + child: Focus( + focusNode: widget.focusNode, + autofocus: widget.autofocus, + canRequestFocus: widget.enabled, + onFocusChange: _handleFocusChange, + child: widget.child, + ), + ); + if (widget.enabled && widget.actions != null && widget.actions.isNotEmpty) { + child = Actions(actions: widget.actions, child: child); + } + if (widget.enabled && widget.shortcuts != null && widget.shortcuts.isNotEmpty) { + child = Shortcuts(shortcuts: widget.shortcuts, child: child); + } + return child; + } +} + /// An [Action], that, as the name implies, does nothing. /// /// This action is bound to the [Intent.doNothing] intent inside of diff --git a/packages/flutter/lib/src/widgets/focus_scope.dart b/packages/flutter/lib/src/widgets/focus_scope.dart index 2585db92af..3c433727bf 100644 --- a/packages/flutter/lib/src/widgets/focus_scope.dart +++ b/packages/flutter/lib/src/widgets/focus_scope.dart @@ -325,7 +325,6 @@ class Focus extends StatefulWidget { class _FocusState extends State { FocusNode _internalNode; FocusNode get focusNode => widget.focusNode ?? _internalNode; - bool _hasFocus; bool _hasPrimaryFocus; bool _canRequestFocus; bool _didAutofocus = false; @@ -347,7 +346,6 @@ class _FocusState extends State { _focusAttachment = focusNode.attach(context, onKey: widget.onKey); focusNode.skipTraversal = widget.skipTraversal ?? focusNode.skipTraversal; focusNode.canRequestFocus = widget.canRequestFocus ?? focusNode.canRequestFocus; - _hasFocus = focusNode.hasFocus; _canRequestFocus = focusNode.canRequestFocus; _hasPrimaryFocus = focusNode.hasPrimaryFocus; @@ -425,22 +423,19 @@ class _FocusState extends State { } void _handleFocusChanged() { - if (_hasFocus != focusNode.hasFocus) { - setState(() { - _hasFocus = focusNode.hasFocus; - }); - if (widget.onFocusChange != null) { - widget.onFocusChange(focusNode.hasFocus); - } + final bool hasPrimaryFocus = focusNode.hasPrimaryFocus; + final bool canRequestFocus = focusNode.canRequestFocus; + if (widget.onFocusChange != null) { + widget.onFocusChange(focusNode.hasFocus); } - if (_hasPrimaryFocus != focusNode.hasPrimaryFocus) { + if (_hasPrimaryFocus != hasPrimaryFocus) { setState(() { - _hasPrimaryFocus = focusNode.hasPrimaryFocus; + _hasPrimaryFocus = hasPrimaryFocus; }); } - if (_canRequestFocus != focusNode.canRequestFocus) { + if (_canRequestFocus != canRequestFocus) { setState(() { - _canRequestFocus = focusNode.canRequestFocus; + _canRequestFocus = canRequestFocus; }); } } diff --git a/packages/flutter/lib/src/widgets/shortcuts.dart b/packages/flutter/lib/src/widgets/shortcuts.dart index a88ea60227..58df560bdb 100644 --- a/packages/flutter/lib/src/widgets/shortcuts.dart +++ b/packages/flutter/lib/src/widgets/shortcuts.dart @@ -254,11 +254,13 @@ class Shortcuts extends StatefulWidget { /// [shortcuts] change materially. final ShortcutManager manager; - /// The map of shortcuts that the [manager] will be given to manage. + /// {@template flutter.widgets.shortcuts.shortcuts} + /// The map of shortcuts that the [ShortcutManager] will be given to manage. /// /// For performance reasons, it is recommended that a pre-built map is passed /// in here (e.g. a final variable from your widget class) instead of defining /// it inline in the build function. + /// {@endtemplate} final Map shortcuts; /// The child widget for this [Shortcuts] widget. diff --git a/packages/flutter/test/material/checkbox_test.dart b/packages/flutter/test/material/checkbox_test.dart index a387ebb52e..bcc85f1b9e 100644 --- a/packages/flutter/test/material/checkbox_test.dart +++ b/packages/flutter/test/material/checkbox_test.dart @@ -68,7 +68,7 @@ void main() { ), )); - expect(tester.getSemantics(find.byType(Focus)), matchesSemantics( + expect(tester.getSemantics(find.byType(Focus).last), matchesSemantics( hasCheckedState: true, hasEnabledState: true, isEnabled: true, @@ -83,7 +83,7 @@ void main() { ), )); - expect(tester.getSemantics(find.byType(Focus)), matchesSemantics( + expect(tester.getSemantics(find.byType(Focus).last), matchesSemantics( hasCheckedState: true, hasEnabledState: true, isChecked: true, @@ -99,10 +99,9 @@ void main() { ), )); - expect(tester.getSemantics(find.byType(Focus)), matchesSemantics( + expect(tester.getSemantics(find.byType(Focus).last), matchesSemantics( hasCheckedState: true, hasEnabledState: true, - isFocusable: true, )); await tester.pumpWidget(const Material( @@ -112,7 +111,7 @@ void main() { ), )); - expect(tester.getSemantics(find.byType(Focus)), matchesSemantics( + expect(tester.getSemantics(find.byType(Focus).last), matchesSemantics( hasCheckedState: true, hasEnabledState: true, isChecked: true, @@ -134,7 +133,7 @@ void main() { ), )); - expect(tester.getSemantics(find.byType(Focus)), matchesSemantics( + expect(tester.getSemantics(find.byType(Focus).last), matchesSemantics( label: 'foo', textDirection: TextDirection.ltr, hasCheckedState: true, diff --git a/packages/flutter/test/material/radio_test.dart b/packages/flutter/test/material/radio_test.dart index dbfbdc3df9..02fe0774bf 100644 --- a/packages/flutter/test/material/radio_test.dart +++ b/packages/flutter/test/material/radio_test.dart @@ -180,12 +180,11 @@ void main() { expect(semantics, hasSemantics(TestSemantics.root( children: [ TestSemantics.rootChild( - id: 1, + id: 2, flags: [ - SemanticsFlag.isInMutuallyExclusiveGroup, SemanticsFlag.hasCheckedState, SemanticsFlag.hasEnabledState, - SemanticsFlag.isFocusable, + SemanticsFlag.isInMutuallyExclusiveGroup, ], ), ], @@ -202,12 +201,12 @@ void main() { expect(semantics, hasSemantics(TestSemantics.root( children: [ TestSemantics.rootChild( - id: 1, + id: 2, flags: [ - SemanticsFlag.isInMutuallyExclusiveGroup, SemanticsFlag.hasCheckedState, SemanticsFlag.isChecked, SemanticsFlag.hasEnabledState, + SemanticsFlag.isInMutuallyExclusiveGroup, ], ), ], @@ -396,6 +395,7 @@ void main() { } await tester.pumpWidget(buildApp()); + await tester.pump(); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byKey(radioKey))), @@ -415,6 +415,7 @@ void main() { // Check when the radio isn't selected. groupValue = 1; await tester.pumpWidget(buildApp()); + await tester.pump(); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byKey(radioKey))), @@ -429,6 +430,7 @@ void main() { // Check when the radio is selected, but disabled. groupValue = 0; await tester.pumpWidget(buildApp(enabled: false)); + await tester.pump(); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byKey(radioKey))), diff --git a/packages/flutter/test/widgets/actions_test.dart b/packages/flutter/test/widgets/actions_test.dart index 1a7454f054..39e4eaa60d 100644 --- a/packages/flutter/test/widgets/actions_test.dart +++ b/packages/flutter/test/widgets/actions_test.dart @@ -3,7 +3,9 @@ // found in the LICENSE file. import 'package:flutter/foundation.dart'; +import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -38,7 +40,7 @@ class TestDispatcher1 extends TestDispatcher { } void main() { - test('$Action passes parameters on when invoked.', () { + test('Action passes parameters on when invoked.', () { bool invoked = false; FocusNode passedNode; final TestAction action = TestAction(onInvoke: (FocusNode node, Intent invocation) { @@ -52,7 +54,7 @@ void main() { expect(invoked, isTrue); }); group(ActionDispatcher, () { - test('$ActionDispatcher invokes actions when asked.', () { + test('ActionDispatcher invokes actions when asked.', () { bool invoked = false; FocusNode passedNode; const ActionDispatcher dispatcher = ActionDispatcher(); @@ -94,7 +96,7 @@ 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; FocusNode passedNode; @@ -124,7 +126,7 @@ void main() { expect(result, isTrue); expect(invoked, isTrue); }); - 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 Intent intent = Intent(TestAction.key); @@ -159,7 +161,7 @@ void main() { expect(invoked, isTrue); expect(invokedIntent, equals(intent)); }); - testWidgets('$Actions can invoke actions in ancestor dispatcher', (WidgetTester tester) async { + testWidgets('Actions can invoke actions in ancestor dispatcher', (WidgetTester tester) async { final GlobalKey containerKey = GlobalKey(); bool invoked = false; const Intent intent = Intent(TestAction.key); @@ -200,7 +202,7 @@ void main() { expect(invokedAction, equals(testAction)); expect(invokedDispatcher.runtimeType, equals(TestDispatcher1)); }); - testWidgets("$Actions can invoke actions in ancestor dispatcher if a lower one isn't specified", (WidgetTester tester) async { + 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 Intent intent = Intent(TestAction.key); @@ -240,7 +242,7 @@ void main() { expect(invokedAction, equals(testAction)); expect(invokedDispatcher.runtimeType, equals(TestDispatcher1)); }); - testWidgets('$Actions widget can be found with of', (WidgetTester tester) async { + testWidgets('Actions widget can be found with of', (WidgetTester tester) async { final GlobalKey containerKey = GlobalKey(); final ActionDispatcher testDispatcher = TestDispatcher1(postInvoke: collect); @@ -259,9 +261,77 @@ void main() { ); expect(dispatcher, equals(testDispatcher)); }); + 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; + const Intent intent = Intent(TestAction.key); + final FocusNode focusNode = FocusNode(debugLabel: 'Test Node'); + final Action testAction = TestAction( + onInvoke: (FocusNode node, Intent invocation) { + invoked = true; + }, + ); + bool hovering = false; + bool focusing = false; + + Future buildTest(bool enabled) async { + await tester.pumpWidget( + Center( + child: Actions( + dispatcher: TestDispatcher1(postInvoke: collect), + actions: const {}, + child: FocusableActionDetector( + enabled: enabled, + focusNode: focusNode, + shortcuts: { + LogicalKeySet(LogicalKeyboardKey.enter): intent, + }, + actions: { + TestAction.key: () => testAction, + }, + onShowHoverHighlight: (bool value) => hovering = value, + onShowFocusHighlight: (bool value) => focusing = value, + child: Container(width: 100, height: 100, key: containerKey), + ), + ), + ), + ); + return tester.pump(); + } + await buildTest(true); + focusNode.requestFocus(); + await tester.pump(); + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); + addTearDown(gesture.removePointer); + await gesture.moveTo(tester.getCenter(find.byKey(containerKey))); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + expect(hovering, isTrue); + expect(focusing, isTrue); + expect(invoked, isTrue); + + invoked = false; + await buildTest(false); + expect(hovering, isFalse); + expect(focusing, isFalse); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pump(); + expect(invoked, isFalse); + await buildTest(true); + expect(focusing, isFalse); + expect(hovering, isTrue); + await buildTest(false); + expect(focusing, isFalse); + expect(hovering, isFalse); + await gesture.moveTo(Offset.zero); + await buildTest(true); + expect(hovering, isFalse); + expect(focusing, isFalse); + }); }); group('Diagnostics', () { - testWidgets('default $Intent debugFillProperties', (WidgetTester tester) async { + testWidgets('default Intent debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const Intent(ValueKey('foo')).debugFillProperties(builder); @@ -275,7 +345,7 @@ void main() { expect(description, equals(['key: [<\'foo\'>]'])); }); - testWidgets('$CallbackAction debugFillProperties', (WidgetTester tester) async { + testWidgets('CallbackAction debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); CallbackAction( @@ -292,7 +362,7 @@ void main() { expect(description, equals(['intentKey: [<\'foo\'>]'])); }); - testWidgets('default $Actions debugFillProperties', (WidgetTester tester) async { + testWidgets('default Actions debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); Actions( @@ -311,7 +381,7 @@ void main() { expect(description[0], equalsIgnoringHashCodes('dispatcher: ActionDispatcher#00000')); expect(description[1], equals('actions: {}')); }); - testWidgets('$Actions implements debugFillProperties', (WidgetTester tester) async { + testWidgets('Actions implements debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); Actions(