Unverified Commit 5bb8d8fc authored by Tong Mu's avatar Tong Mu Committed by GitHub

Split Mouse from Listener (#36217)

- Splits on{Enter,Hover,Exit} from Listener to MouseRegion. Deprecated API is kept for compatibility.
- Splits on{Enter,Hover,Exit} from RenderPointerListener to RenderMouseRegion.
parent ced20783
<<skip until matching line>>
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following assertion was thrown building
RawGestureDetector-\[LabeledGlobalKey<RawGestureDetectorState>#.+\]\(state:
RawGestureDetectorState#.+\(gestures: <none>, behavior: opaque\)\):
The following assertion was thrown building Listener
'package:flutter\/src\/painting\/basic_types\.dart': Failed assertion: line 223 pos 10: 'textDirection
!= null': is not true\.
......
<<skip until matching line>>
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following assertion was thrown building
RawGestureDetector-\[LabeledGlobalKey<RawGestureDetectorState>#.+\]\(state:
RawGestureDetectorState#.+\(gestures: <none>, behavior: opaque\)\):
The following assertion was thrown building Listener
'package:flutter\/src\/painting\/basic_types\.dart': Failed assertion: line 223 pos 10: 'textDirection
!= null': is not true\.
......
......@@ -685,8 +685,8 @@ class _InkResponseState<T extends InkResponse> extends State<T> with AutomaticKe
bool get enabled => _isWidgetEnabled(widget);
void _handlePointerEnter(PointerEnterEvent event) => _handleHoverChange(true);
void _handlePointerExit(PointerExitEvent event) => _handleHoverChange(false);
void _handleMouseEnter(PointerEnterEvent event) => _handleHoverChange(true);
void _handleMouseExit(PointerExitEvent event) => _handleHoverChange(false);
void _handleHoverChange(bool hovering) {
if (_hovering != hovering) {
_hovering = hovering;
......@@ -702,10 +702,9 @@ class _InkResponseState<T extends InkResponse> extends State<T> with AutomaticKe
_highlights[type]?.color = getHighlightColorForType(type);
}
_currentSplash?.color = widget.splashColor ?? Theme.of(context).splashColor;
return Listener(
onPointerEnter: enabled ? _handlePointerEnter : null,
onPointerExit: enabled ? _handlePointerExit : null,
behavior: HitTestBehavior.translucent,
return MouseRegion(
onEnter: enabled ? _handleMouseEnter : null,
onExit: enabled ? _handleMouseExit : null,
child: GestureDetector(
onTapDown: enabled ? _handleTapDown : null,
onTap: enabled ? () => _handleTap(context) : null,
......
......@@ -887,8 +887,8 @@ class _TextFieldState extends State<TextField> with AutomaticKeepAliveClientMixi
super.deactivate();
}
void _handlePointerEnter(PointerEnterEvent event) => _handleHover(true);
void _handlePointerExit(PointerExitEvent event) => _handleHover(false);
void _handleMouseEnter(PointerEnterEvent event) => _handleHover(true);
void _handleMouseExit(PointerExitEvent event) => _handleHover(false);
void _handleHover(bool hovering) {
if (hovering != _isHovering) {
......@@ -1020,9 +1020,9 @@ class _TextFieldState extends State<TextField> with AutomaticKeepAliveClientMixi
_effectiveController.selection = TextSelection.collapsed(offset: _effectiveController.text.length);
_requestKeyboard();
},
child: Listener(
onPointerEnter: _handlePointerEnter,
onPointerExit: _handlePointerExit,
child: MouseRegion(
onEnter: _handleMouseEnter,
onExit: _handleMouseExit,
child: IgnorePointer(
ignoring: !(widget.enabled ?? widget.decoration?.enabled ?? true),
child: _selectionGestureDetectorBuilder.buildGestureDetector(
......
......@@ -399,9 +399,9 @@ class _TooltipState extends State<Tooltip> with SingleTickerProviderStateMixin {
// Only check for hovering if there is a mouse connected.
if (_mouseIsConnected) {
result = Listener(
onPointerEnter: (PointerEnterEvent event) => _showTooltip(),
onPointerExit: (PointerExitEvent event) => _hideTooltip(),
result = MouseRegion(
onEnter: (PointerEnterEvent event) => _showTooltip(),
onExit: (PointerExitEvent event) => _hideTooltip(),
child: result,
);
}
......
......@@ -2460,15 +2460,18 @@ typedef PointerCancelEventListener = void Function(PointerCancelEvent event);
/// Used by [Listener] and [RenderPointerListener].
typedef PointerSignalEventListener = void Function(PointerSignalEvent event);
/// Calls callbacks in response to pointer events.
/// Calls callbacks in response to common pointer events.
///
/// It responds to events that can construct gestures, such as when the
/// pointer is pressed, moved, then released or canceled.
///
/// It does not respond to events that are exclusive to mouse, such as when the
/// mouse enters, exits or hovers a region without pressing any buttons. For
/// these events, use [RenderMouseRegion].
///
/// If it has a child, defers to the child for sizing behavior.
///
/// If it does not have a child, grows to fit the parent-provided constraints.
///
/// The [onPointerEnter], [onPointerHover], and [onPointerExit] events are only
/// relevant to and fired by pointers that can hover (e.g. mouse pointers, but
/// not most touch pointers).
class RenderPointerListener extends RenderProxyBoxWithHitTestBehavior {
/// Creates a render object that forwards pointer events to callbacks.
///
......@@ -2476,27 +2479,12 @@ class RenderPointerListener extends RenderProxyBoxWithHitTestBehavior {
RenderPointerListener({
this.onPointerDown,
this.onPointerMove,
PointerEnterEventListener onPointerEnter,
PointerHoverEventListener onPointerHover,
PointerExitEventListener onPointerExit,
this.onPointerUp,
this.onPointerCancel,
this.onPointerSignal,
HitTestBehavior behavior = HitTestBehavior.deferToChild,
RenderBox child,
}) : _onPointerEnter = onPointerEnter,
_onPointerHover = onPointerHover,
_onPointerExit = onPointerExit,
super(behavior: behavior, child: child) {
if (_onPointerEnter != null || _onPointerHover != null || _onPointerExit != null) {
_hoverAnnotation = MouseTrackerAnnotation(
onEnter: _onPointerEnter,
onHover: _onPointerHover,
onExit: _onPointerExit,
);
}
_mouseIsConnected = RendererBinding.instance.mouseTracker.mouseIsConnected;
}
}) : super(behavior: behavior, child: child);
/// Called when a pointer comes into contact with the screen (for touch
/// pointers), or has its button pressed (for mouse pointers) at this widget's
......@@ -2506,55 +2494,129 @@ class RenderPointerListener extends RenderProxyBoxWithHitTestBehavior {
/// Called when a pointer that triggered an [onPointerDown] changes position.
PointerMoveEventListener onPointerMove;
/// Called when a pointer that triggered an [onPointerDown] is no longer in
/// contact with the screen.
PointerUpEventListener onPointerUp;
/// Called when the input from a pointer that triggered an [onPointerDown] is
/// no longer directed towards this receiver.
PointerCancelEventListener onPointerCancel;
/// Called when a pointer signal occurs over this object.
PointerSignalEventListener onPointerSignal;
@override
void performResize() {
size = constraints.biggest;
}
@override
void handleEvent(PointerEvent event, HitTestEntry entry) {
assert(debugHandleEvent(event, entry));
if (onPointerDown != null && event is PointerDownEvent)
return onPointerDown(event);
if (onPointerMove != null && event is PointerMoveEvent)
return onPointerMove(event);
if (onPointerUp != null && event is PointerUpEvent)
return onPointerUp(event);
if (onPointerCancel != null && event is PointerCancelEvent)
return onPointerCancel(event);
if (onPointerSignal != null && event is PointerSignalEvent)
return onPointerSignal(event);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
final List<String> listeners = <String>[];
if (onPointerDown != null)
listeners.add('down');
if (onPointerMove != null)
listeners.add('move');
if (onPointerUp != null)
listeners.add('up');
if (onPointerCancel != null)
listeners.add('cancel');
if (onPointerSignal != null)
listeners.add('signal');
if (listeners.isEmpty)
listeners.add('<none>');
properties.add(IterableProperty<String>('listeners', listeners));
// TODO(jacobr): add raw listeners to the diagnostics data.
}
}
/// Calls callbacks in response to pointer events that are exclusive to mice.
///
/// Simply put, it responds to events that are related to hovering,
/// i.e. when the mouse enters, exits or hovers a region without pressing.
///
/// It does not respond to common events that construct gestures, such as when
/// the pointer is pressed, moved, then released or canceled. For these events,
/// use [RenderPointerListener].
///
/// If it has a child, it defers to the child for sizing behavior.
///
/// If it does not have a child, it grows to fit the parent-provided constraints.
class RenderMouseRegion extends RenderProxyBox {
/// Creates a render object that forwards pointer events to callbacks.
RenderMouseRegion({
PointerEnterEventListener onEnter,
PointerHoverEventListener onHover,
PointerExitEventListener onExit,
RenderBox child,
}) : _onEnter = onEnter,
_onHover = onHover,
_onExit = onExit,
super(child) {
if (_onEnter != null || _onHover != null || _onExit != null) {
_hoverAnnotation = MouseTrackerAnnotation(
onEnter: _onEnter,
onHover: _onHover,
onExit: _onExit,
);
}
_mouseIsConnected = RendererBinding.instance.mouseTracker.mouseIsConnected;
}
/// Called when a hovering pointer enters the region for this widget.
///
/// If this is a mouse pointer, this will fire when the mouse pointer enters
/// the region defined by this widget.
PointerEnterEventListener get onPointerEnter => _onPointerEnter;
set onPointerEnter(PointerEnterEventListener value) {
if (_onPointerEnter != value) {
_onPointerEnter = value;
PointerEnterEventListener get onEnter => _onEnter;
set onEnter(PointerEnterEventListener value) {
if (_onEnter != value) {
_onEnter = value;
_updateAnnotations();
}
}
PointerEnterEventListener _onPointerEnter;
PointerEnterEventListener _onEnter;
/// Called when a pointer that has not triggered an [onPointerDown] changes
/// position.
///
/// Typically only triggered for mouse pointers.
PointerHoverEventListener get onPointerHover => _onPointerHover;
set onPointerHover(PointerHoverEventListener value) {
if (_onPointerHover != value) {
_onPointerHover = value;
PointerHoverEventListener get onHover => _onHover;
set onHover(PointerHoverEventListener value) {
if (_onHover != value) {
_onHover = value;
_updateAnnotations();
}
}
PointerHoverEventListener _onPointerHover;
PointerHoverEventListener _onHover;
/// Called when a hovering pointer leaves the region for this widget.
///
/// If this is a mouse pointer, this will fire when the mouse pointer leaves
/// the region defined by this widget.
PointerExitEventListener get onPointerExit => _onPointerExit;
set onPointerExit(PointerExitEventListener value) {
if (_onPointerExit != value) {
_onPointerExit = value;
PointerExitEventListener get onExit => _onExit;
set onExit(PointerExitEventListener value) {
if (_onExit != value) {
_onExit = value;
_updateAnnotations();
}
}
PointerExitEventListener _onPointerExit;
/// Called when a pointer that triggered an [onPointerDown] is no longer in
/// contact with the screen.
PointerUpEventListener onPointerUp;
/// Called when the input from a pointer that triggered an [onPointerDown] is
/// no longer directed towards this receiver.
PointerCancelEventListener onPointerCancel;
/// Called when a pointer signal occurs over this object.
PointerSignalEventListener onPointerSignal;
PointerExitEventListener _onExit;
// Object used for annotation of the layer used for hover hit detection.
MouseTrackerAnnotation _hoverAnnotation;
......@@ -2567,7 +2629,7 @@ class RenderPointerListener extends RenderProxyBoxWithHitTestBehavior {
MouseTrackerAnnotation get hoverAnnotation => _hoverAnnotation;
void _updateAnnotations() {
assert(_hoverAnnotation == null || _onPointerEnter != _hoverAnnotation.onEnter || _onPointerHover != _hoverAnnotation.onHover || _onPointerExit != _hoverAnnotation.onExit,
assert(_hoverAnnotation == null || _onEnter != _hoverAnnotation.onEnter || _onHover != _hoverAnnotation.onHover || _onExit != _hoverAnnotation.onExit,
"Shouldn't call _updateAnnotations if nothing has changed.");
bool changed = false;
final bool hadHoverAnnotation = _hoverAnnotation != null;
......@@ -2575,11 +2637,11 @@ class RenderPointerListener extends RenderProxyBoxWithHitTestBehavior {
RendererBinding.instance.mouseTracker.detachAnnotation(_hoverAnnotation);
changed = true;
}
if (_onPointerEnter != null || _onPointerHover != null || _onPointerExit != null) {
if (_onEnter != null || _onHover != null || _onExit != null) {
_hoverAnnotation = MouseTrackerAnnotation(
onEnter: _onPointerEnter,
onHover: _onPointerHover,
onExit: _onPointerExit,
onEnter: _onEnter,
onHover: _onHover,
onExit: _onExit,
);
if (attached) {
RendererBinding.instance.mouseTracker.attachAnnotation(_hoverAnnotation);
......@@ -2674,43 +2736,16 @@ class RenderPointerListener extends RenderProxyBoxWithHitTestBehavior {
size = constraints.biggest;
}
@override
void handleEvent(PointerEvent event, HitTestEntry entry) {
assert(debugHandleEvent(event, entry));
// The onPointerEnter, onPointerHover, and onPointerExit events are are
// triggered from within the MouseTracker, not here.
if (onPointerDown != null && event is PointerDownEvent)
return onPointerDown(event);
if (onPointerMove != null && event is PointerMoveEvent)
return onPointerMove(event);
if (onPointerUp != null && event is PointerUpEvent)
return onPointerUp(event);
if (onPointerCancel != null && event is PointerCancelEvent)
return onPointerCancel(event);
if (onPointerSignal != null && event is PointerSignalEvent)
return onPointerSignal(event);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
final List<String> listeners = <String>[];
if (onPointerDown != null)
listeners.add('down');
if (onPointerMove != null)
listeners.add('move');
if (onPointerEnter != null)
if (onEnter != null)
listeners.add('enter');
if (onPointerHover != null)
if (onHover != null)
listeners.add('hover');
if (onPointerExit != null)
if (onExit != null)
listeners.add('exit');
if (onPointerUp != null)
listeners.add('up');
if (onPointerCancel != null)
listeners.add('cancel');
if (onPointerSignal != null)
listeners.add('signal');
if (listeners.isEmpty)
listeners.add('<none>');
properties.add(IterableProperty<String>('listeners', listeners));
......
......@@ -5433,7 +5433,14 @@ class WidgetToRenderBoxAdapter extends LeafRenderObjectWidget {
// EVENT HANDLING
/// A widget that calls callbacks in response to pointer events.
/// A widget that calls callbacks in response to common pointer events.
///
/// It listens to events that can construct gestures, such as when the
/// pointer is pressed, moved, then released or canceled.
///
/// It does not listen to events that are exclusive to mouse, such as when the
/// mouse enters, exits or hovers a region without pressing any buttons. For
/// these events, use [MouseRegion].
///
/// Rather than listening for raw pointer events, consider listening for
/// higher-level gestures using [GestureDetector].
......@@ -5446,32 +5453,32 @@ class WidgetToRenderBoxAdapter extends LeafRenderObjectWidget {
/// it does not have a child, it grows to fit the parent instead.
///
/// {@tool snippet --template=stateful_widget_scaffold}
/// This example makes a [Container] react to being entered by a mouse
/// pointer, showing a count of the number of entries and exits.
/// This example makes a [Container] react to being touched, showing a count of
/// the number of pointer downs and ups.
///
/// ```dart imports
/// import 'package:flutter/gestures.dart';
/// import 'package:flutter/widgets.dart';
/// ```
///
/// ```dart
/// int _enterCounter = 0;
/// int _exitCounter = 0;
/// int _downCounter = 0;
/// int _upCounter = 0;
/// double x = 0.0;
/// double y = 0.0;
///
/// void _incrementCounter(PointerEnterEvent details) {
/// void _incrementDown(PointerEvent details) {
/// _updateLocation(details);
/// setState(() {
/// _enterCounter++;
/// _downCounter++;
/// });
/// }
///
/// void _decrementCounter(PointerExitEvent details) {
/// void _incrementUp(PointerEvent details) {
/// _updateLocation(details);
/// setState(() {
/// _exitCounter++;
/// _upCounter++;
/// });
/// }
///
/// void _updateLocation(PointerHoverEvent details) {
/// void _updateLocation(PointerEvent details) {
/// setState(() {
/// x = details.position.dx;
/// y = details.position.dy;
......@@ -5484,17 +5491,17 @@ class WidgetToRenderBoxAdapter extends LeafRenderObjectWidget {
/// child: ConstrainedBox(
/// constraints: new BoxConstraints.tight(Size(300.0, 200.0)),
/// child: Listener(
/// onPointerEnter: _incrementCounter,
/// onPointerHover: _updateLocation,
/// onPointerExit: _decrementCounter,
/// onPointerDown: _incrementDown,
/// onPointerMove: _updateLocation,
/// onPointerUp: _incrementUp,
/// child: Container(
/// color: Colors.lightBlueAccent,
/// child: Column(
/// mainAxisAlignment: MainAxisAlignment.center,
/// children: <Widget>[
/// Text('You have pointed at this box this many times:'),
/// Text('You have pressed or released in this area this many times:'),
/// Text(
/// '$_enterCounter Entries\n$_exitCounter Exits',
/// '$_downCounter presses\n$_upCounter releases',
/// style: Theme.of(context).textTheme.display1,
/// ),
/// Text(
......@@ -5509,11 +5516,7 @@ class WidgetToRenderBoxAdapter extends LeafRenderObjectWidget {
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [MouseTracker] an object that tracks mouse locations in the [GestureBinding].
class Listener extends SingleChildRenderObjectWidget {
class Listener extends StatelessWidget {
/// Creates a widget that forwards point events to callbacks.
///
/// The [behavior] argument defaults to [HitTestBehavior.deferToChild].
......@@ -5521,16 +5524,25 @@ class Listener extends SingleChildRenderObjectWidget {
Key key,
this.onPointerDown,
this.onPointerMove,
this.onPointerEnter,
this.onPointerExit,
this.onPointerHover,
// We have to ignore the lint rule here in order to use deprecated
// parameters and keep backward compatibility.
// TODO(tongmu): After it goes stable, remove these 3 parameters from Listener
// and Listener should no longer need an intermediate class _PointerListener.
// https://github.com/flutter/flutter/issues/36085
@Deprecated('Use MouseRegion.onEnter instead')
this.onPointerEnter, // ignore: deprecated_member_use_from_same_package
@Deprecated('Use MouseRegion.onExit instead')
this.onPointerExit, // ignore: deprecated_member_use_from_same_package
@Deprecated('Use MouseRegion.onHover instead')
this.onPointerHover, // ignore: deprecated_member_use_from_same_package
this.onPointerUp,
this.onPointerCancel,
this.onPointerSignal,
this.behavior = HitTestBehavior.deferToChild,
Widget child,
}) : assert(behavior != null),
super(key: key, child: child);
_child = child,
super(key: key);
/// Called when a pointer comes into contact with the screen (for touch
/// pointers), or has its button pressed (for mouse pointers) at this widget's
......@@ -5581,17 +5593,64 @@ class Listener extends SingleChildRenderObjectWidget {
/// How to behave during hit testing.
final HitTestBehavior behavior;
// The widget listened to by the listener.
//
// The reason why we don't expose it is that once the deprecated methods are
// removed, Listener will no longer need to store the child, but will pass
// the child to `super` instead.
final Widget _child;
@override
_ListenerElement createElement() => _ListenerElement(this);
Widget build(BuildContext context) {
Widget result = _child;
if (onPointerEnter != null ||
onPointerExit != null ||
onPointerHover != null) {
result = MouseRegion(
onEnter: onPointerEnter,
onExit: onPointerExit,
onHover: onPointerHover,
child: result,
);
}
result = _PointerListener(
onPointerDown: onPointerDown,
onPointerUp: onPointerUp,
onPointerMove: onPointerMove,
onPointerCancel: onPointerCancel,
onPointerSignal: onPointerSignal,
behavior: behavior,
child: result,
);
return result;
}
}
class _PointerListener extends SingleChildRenderObjectWidget {
const _PointerListener({
Key key,
this.onPointerDown,
this.onPointerMove,
this.onPointerUp,
this.onPointerCancel,
this.onPointerSignal,
this.behavior = HitTestBehavior.deferToChild,
Widget child,
}) : assert(behavior != null),
super(key: key, child: child);
final PointerDownEventListener onPointerDown;
final PointerMoveEventListener onPointerMove;
final PointerUpEventListener onPointerUp;
final PointerCancelEventListener onPointerCancel;
final PointerSignalEventListener onPointerSignal;
final HitTestBehavior behavior;
@override
RenderPointerListener createRenderObject(BuildContext context) {
return RenderPointerListener(
onPointerDown: onPointerDown,
onPointerMove: onPointerMove,
onPointerEnter: onPointerEnter,
onPointerHover: onPointerHover,
onPointerExit: onPointerExit,
onPointerUp: onPointerUp,
onPointerCancel: onPointerCancel,
onPointerSignal: onPointerSignal,
......@@ -5604,9 +5663,6 @@ class Listener extends SingleChildRenderObjectWidget {
renderObject
..onPointerDown = onPointerDown
..onPointerMove = onPointerMove
..onPointerEnter = onPointerEnter
..onPointerHover = onPointerHover
..onPointerExit = onPointerExit
..onPointerUp = onPointerUp
..onPointerCancel = onPointerCancel
..onPointerSignal = onPointerSignal
......@@ -5621,12 +5677,6 @@ class Listener extends SingleChildRenderObjectWidget {
listeners.add('down');
if (onPointerMove != null)
listeners.add('move');
if (onPointerEnter != null)
listeners.add('enter');
if (onPointerExit != null)
listeners.add('exit');
if (onPointerHover != null)
listeners.add('hover');
if (onPointerUp != null)
listeners.add('up');
if (onPointerCancel != null)
......@@ -5638,20 +5688,158 @@ class Listener extends SingleChildRenderObjectWidget {
}
}
/// A widget that tracks the movement of mice, even when no button is pressed.
///
/// It does not listen to events that can construct gestures, such as when the
/// pointer is pressed, moved, then released or canceled. For these events,
/// use [Listener], or more preferably, [GestureDetector].
///
/// ## Layout behavior
///
/// _See [BoxConstraints] for an introduction to box layout models._
///
/// If it has a child, this widget defers to the child for sizing behavior. If
/// it does not have a child, it grows to fit the parent instead.
///
/// {@tool snippet --template=stateful_widget_scaffold}
/// This example makes a [Container] react to being entered by a mouse
/// pointer, showing a count of the number of entries and exits.
///
/// ```dart imports
/// import 'package:flutter/widgets.dart';
/// ```
///
/// ```dart
/// int _enterCounter = 0;
/// int _exitCounter = 0;
/// double x = 0.0;
/// double y = 0.0;
///
/// void _incrementEnter(PointerEvent details) {
/// setState(() {
/// _enterCounter++;
/// });
/// }
/// void _incrementExit(PointerEvent details) {
/// setState(() {
/// _exitCounter++;
/// });
/// }
/// void _updateLocation(PointerEvent details) {
/// setState(() {
/// x = details.position.dx;
/// y = details.position.dy;
/// });
/// }
///
/// @override
/// Widget build(BuildContext context) {
/// return Center(
/// child: ConstrainedBox(
/// constraints: new BoxConstraints.tight(Size(300.0, 200.0)),
/// child: MouseRegion(
/// onEnter: _incrementEnter,
/// onHover: _updateLocation,
/// onExit: _incrementExit,
/// child: Container(
/// color: Colors.lightBlueAccent,
/// child: Column(
/// mainAxisAlignment: MainAxisAlignment.center,
/// children: <Widget>[
/// Text('You have entered or exited this box this many times:'),
/// Text(
/// '$_enterCounter Entries\n$_exitCounter Exits',
/// style: Theme.of(context).textTheme.display1,
/// ),
/// Text(
/// 'The cursor is here: (${x.toStringAsFixed(2)}, ${y.toStringAsFixed(2)})',
/// ),
/// ],
/// ),
/// ),
/// ),
/// ),
/// );
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [Listener], a similar widget that tracks pointer events when the pointer
/// have buttons pressed.
class MouseRegion extends SingleChildRenderObjectWidget {
/// Creates a widget that forwards mouse events to callbacks.
const MouseRegion({
Key key,
this.onEnter,
this.onExit,
this.onHover,
Widget child,
}) : super(key: key, child: child);
/// Called when a mouse pointer (with or without buttons pressed) enters the
/// region defined by this widget, or when the widget appears under the
/// pointer.
final PointerEnterEventListener onEnter;
/// Called when a mouse pointer (with or without buttons pressed) changes
/// position, and the new position is within the region defined by this widget.
final PointerHoverEventListener onHover;
/// Called when a mouse pointer (with or without buttons pressed) leaves the
/// region defined by this widget, or when the widget disappears from under
/// the pointer.
final PointerExitEventListener onExit;
@override
_ListenerElement createElement() => _ListenerElement(this);
@override
RenderMouseRegion createRenderObject(BuildContext context) {
return RenderMouseRegion(
onEnter: onEnter,
onHover: onHover,
onExit: onExit,
);
}
@override
void updateRenderObject(BuildContext context, RenderMouseRegion renderObject) {
renderObject
..onEnter = onEnter
..onHover = onHover
..onExit = onExit;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
final List<String> listeners = <String>[];
if (onEnter != null)
listeners.add('enter');
if (onExit != null)
listeners.add('exit');
if (onHover != null)
listeners.add('hover');
properties.add(IterableProperty<String>('listeners', listeners, ifEmpty: '<none>'));
}
}
class _ListenerElement extends SingleChildRenderObjectElement {
_ListenerElement(SingleChildRenderObjectWidget widget) : super(widget);
@override
void activate() {
super.activate();
final RenderPointerListener renderPointerListener = renderObject;
renderPointerListener.postActivate();
final RenderMouseRegion renderMouseListener = renderObject;
renderMouseListener.postActivate();
}
@override
void deactivate() {
final RenderPointerListener renderPointerListener = renderObject;
renderPointerListener.preDeactivate();
final RenderMouseRegion renderMouseListener = renderObject;
renderMouseListener.preDeactivate();
super.deactivate();
}
}
......
// Copyright 2019 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/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter/gestures.dart';
// The tests in this file are moved from listener_test.dart, which tests several
// deprecated APIs. The file should be removed once these parameters are.
// ignore_for_file: deprecated_member_use_from_same_package
// We have to ignore the lint rule here because we need to use the deprecated
// callbacks in order to test them.
class HoverClient extends StatefulWidget {
const HoverClient({Key key, this.onHover, this.child}) : super(key: key);
final ValueChanged<bool> onHover;
final Widget child;
@override
HoverClientState createState() => HoverClientState();
}
class HoverClientState extends State<HoverClient> {
static int numEntries = 0;
static int numExits = 0;
void _onExit(PointerExitEvent details) {
numExits++;
if (widget.onHover != null) {
widget.onHover(false);
}
}
void _onEnter(PointerEnterEvent details) {
numEntries++;
if (widget.onHover != null) {
widget.onHover(true);
}
}
@override
Widget build(BuildContext context) {
return Listener(
onPointerEnter: _onEnter,
onPointerExit: _onExit,
child: widget.child,
);
}
}
class HoverFeedback extends StatefulWidget {
const HoverFeedback({Key key}) : super(key: key);
@override
_HoverFeedbackState createState() => _HoverFeedbackState();
}
class _HoverFeedbackState extends State<HoverFeedback> {
bool _hovering = false;
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: HoverClient(
onHover: (bool hovering) => setState(() => _hovering = hovering),
child: Text(_hovering ? 'HOVERING' : 'not hovering'),
),
);
}
}
void main() {
group('Listener hover detection', () {
// TODO(tongmu): Remover this group of test after the deprecated callbacks
// onPointer{Enter,Hover,Exit} are removed. They were kept for compatibility,
// and the tests have been copied to mouse_region_test.
// https://github.com/flutter/flutter/issues/36085
setUp((){
HoverClientState.numExits = 0;
HoverClientState.numEntries = 0;
});
testWidgets('detects pointer enter', (WidgetTester tester) async {
PointerEnterEvent enter;
PointerHoverEvent move;
PointerExitEvent exit;
await tester.pumpWidget(Center(
child: Listener(
child: Container(
color: const Color.fromARGB(0xff, 0xff, 0x00, 0x00),
width: 100.0,
height: 100.0,
),
onPointerEnter: (PointerEnterEvent details) => enter = details,
onPointerHover: (PointerHoverEvent details) => move = details,
onPointerExit: (PointerExitEvent details) => exit = details,
),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(const Offset(400.0, 300.0));
await tester.pump();
expect(move, isNotNull);
expect(move.position, equals(const Offset(400.0, 300.0)));
expect(enter, isNotNull);
expect(enter.position, equals(const Offset(400.0, 300.0)));
expect(exit, isNull);
await gesture.removePointer();
});
testWidgets('detects pointer exiting', (WidgetTester tester) async {
PointerEnterEvent enter;
PointerHoverEvent move;
PointerExitEvent exit;
await tester.pumpWidget(Center(
child: Listener(
child: Container(
width: 100.0,
height: 100.0,
),
onPointerEnter: (PointerEnterEvent details) => enter = details,
onPointerHover: (PointerHoverEvent details) => move = details,
onPointerExit: (PointerExitEvent details) => exit = details,
),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(const Offset(400.0, 300.0));
await tester.pump();
move = null;
enter = null;
await gesture.moveTo(const Offset(1.0, 1.0));
await tester.pump();
expect(move, isNull);
expect(enter, isNull);
expect(exit, isNotNull);
expect(exit.position, equals(const Offset(1.0, 1.0)));
await gesture.removePointer();
});
testWidgets('detects pointer exit when widget disappears', (WidgetTester tester) async {
PointerEnterEvent enter;
PointerHoverEvent move;
PointerExitEvent exit;
await tester.pumpWidget(Center(
child: Listener(
child: Container(
width: 100.0,
height: 100.0,
),
onPointerEnter: (PointerEnterEvent details) => enter = details,
onPointerHover: (PointerHoverEvent details) => move = details,
onPointerExit: (PointerExitEvent details) => exit = details,
),
));
final RenderMouseRegion renderListener = tester.renderObject(find.byType(MouseRegion));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(const Offset(400.0, 300.0));
await tester.pump();
expect(move, isNotNull);
expect(move.position, equals(const Offset(400.0, 300.0)));
expect(enter, isNotNull);
expect(enter.position, equals(const Offset(400.0, 300.0)));
expect(exit, isNull);
await tester.pumpWidget(Center(
child: Container(
width: 100.0,
height: 100.0,
),
));
expect(exit, isNotNull);
expect(exit.position, equals(const Offset(400.0, 300.0)));
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener.hoverAnnotation), isFalse);
await gesture.removePointer();
});
testWidgets('Hover works with nested listeners', (WidgetTester tester) async {
final UniqueKey key1 = UniqueKey();
final UniqueKey key2 = UniqueKey();
final List<PointerEnterEvent> enter1 = <PointerEnterEvent>[];
final List<PointerHoverEvent> move1 = <PointerHoverEvent>[];
final List<PointerExitEvent> exit1 = <PointerExitEvent>[];
final List<PointerEnterEvent> enter2 = <PointerEnterEvent>[];
final List<PointerHoverEvent> move2 = <PointerHoverEvent>[];
final List<PointerExitEvent> exit2 = <PointerExitEvent>[];
void clearLists() {
enter1.clear();
move1.clear();
exit1.clear();
enter2.clear();
move2.clear();
exit2.clear();
}
await tester.pumpWidget(Container());
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(const Offset(400.0, 0.0));
await tester.pump();
await tester.pumpWidget(
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Listener(
onPointerEnter: (PointerEnterEvent details) => enter1.add(details),
onPointerHover: (PointerHoverEvent details) => move1.add(details),
onPointerExit: (PointerExitEvent details) => exit1.add(details),
key: key1,
child: Container(
width: 200,
height: 200,
padding: const EdgeInsets.all(50.0),
child: Listener(
key: key2,
onPointerEnter: (PointerEnterEvent details) => enter2.add(details),
onPointerHover: (PointerHoverEvent details) => move2.add(details),
onPointerExit: (PointerExitEvent details) => exit2.add(details),
child: Container(),
),
),
),
],
),
);
final List<RenderObject> listeners = tester.renderObjectList(find.byType(MouseRegion)).toList();
final RenderMouseRegion renderListener1 = listeners[0];
final RenderMouseRegion renderListener2 = listeners[1];
Offset center = tester.getCenter(find.byKey(key2));
await gesture.moveTo(center);
await tester.pump();
expect(move2, isNotEmpty);
expect(enter2, isNotEmpty);
expect(exit2, isEmpty);
expect(move1, isNotEmpty);
expect(move1.last.position, equals(center));
expect(enter1, isNotEmpty);
expect(enter1.last.position, equals(center));
expect(exit1, isEmpty);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener1.hoverAnnotation), isTrue);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener2.hoverAnnotation), isTrue);
clearLists();
// Now make sure that exiting the child only triggers the child exit, not
// the parent too.
center = center - const Offset(75.0, 0.0);
await gesture.moveTo(center);
await tester.pumpAndSettle();
expect(move2, isEmpty);
expect(enter2, isEmpty);
expect(exit2, isNotEmpty);
expect(move1, isNotEmpty);
expect(move1.last.position, equals(center));
expect(enter1, isEmpty);
expect(exit1, isEmpty);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener1.hoverAnnotation), isTrue);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener2.hoverAnnotation), isTrue);
clearLists();
await gesture.removePointer();
});
testWidgets('Hover transfers between two listeners', (WidgetTester tester) async {
final UniqueKey key1 = UniqueKey();
final UniqueKey key2 = UniqueKey();
final List<PointerEnterEvent> enter1 = <PointerEnterEvent>[];
final List<PointerHoverEvent> move1 = <PointerHoverEvent>[];
final List<PointerExitEvent> exit1 = <PointerExitEvent>[];
final List<PointerEnterEvent> enter2 = <PointerEnterEvent>[];
final List<PointerHoverEvent> move2 = <PointerHoverEvent>[];
final List<PointerExitEvent> exit2 = <PointerExitEvent>[];
void clearLists() {
enter1.clear();
move1.clear();
exit1.clear();
enter2.clear();
move2.clear();
exit2.clear();
}
await tester.pumpWidget(Container());
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(const Offset(400.0, 0.0));
await tester.pump();
await tester.pumpWidget(
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Listener(
key: key1,
child: Container(
width: 100.0,
height: 100.0,
),
onPointerEnter: (PointerEnterEvent details) => enter1.add(details),
onPointerHover: (PointerHoverEvent details) => move1.add(details),
onPointerExit: (PointerExitEvent details) => exit1.add(details),
),
Listener(
key: key2,
child: Container(
width: 100.0,
height: 100.0,
),
onPointerEnter: (PointerEnterEvent details) => enter2.add(details),
onPointerHover: (PointerHoverEvent details) => move2.add(details),
onPointerExit: (PointerExitEvent details) => exit2.add(details),
),
],
),
);
final List<RenderObject> listeners = tester.renderObjectList(find.byType(MouseRegion)).toList();
final RenderMouseRegion renderListener1 = listeners[0];
final RenderMouseRegion renderListener2 = listeners[1];
final Offset center1 = tester.getCenter(find.byKey(key1));
final Offset center2 = tester.getCenter(find.byKey(key2));
await gesture.moveTo(center1);
await tester.pump();
expect(move1, isNotEmpty);
expect(move1.last.position, equals(center1));
expect(enter1, isNotEmpty);
expect(enter1.last.position, equals(center1));
expect(exit1, isEmpty);
expect(move2, isEmpty);
expect(enter2, isEmpty);
expect(exit2, isEmpty);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener1.hoverAnnotation), isTrue);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener2.hoverAnnotation), isTrue);
clearLists();
await gesture.moveTo(center2);
await tester.pump();
expect(move1, isEmpty);
expect(enter1, isEmpty);
expect(exit1, isNotEmpty);
expect(exit1.last.position, equals(center2));
expect(move2, isNotEmpty);
expect(move2.last.position, equals(center2));
expect(enter2, isNotEmpty);
expect(enter2.last.position, equals(center2));
expect(exit2, isEmpty);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener1.hoverAnnotation), isTrue);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener2.hoverAnnotation), isTrue);
clearLists();
await gesture.moveTo(const Offset(400.0, 450.0));
await tester.pump();
expect(move1, isEmpty);
expect(enter1, isEmpty);
expect(exit1, isEmpty);
expect(move2, isEmpty);
expect(enter2, isEmpty);
expect(exit2, isNotEmpty);
expect(exit2.last.position, equals(const Offset(400.0, 450.0)));
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener1.hoverAnnotation), isTrue);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener2.hoverAnnotation), isTrue);
clearLists();
await tester.pumpWidget(Container());
expect(move1, isEmpty);
expect(enter1, isEmpty);
expect(exit1, isEmpty);
expect(move2, isEmpty);
expect(enter2, isEmpty);
expect(exit2, isEmpty);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener1.hoverAnnotation), isFalse);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener2.hoverAnnotation), isFalse);
await gesture.removePointer();
});
testWidgets('needsCompositing set when parent class needsCompositing is set', (WidgetTester tester) async {
await tester.pumpWidget(
Listener(
onPointerEnter: (PointerEnterEvent _) {},
child: const Opacity(opacity: 0.5, child: Placeholder()),
),
);
RenderPointerListener listener = tester.renderObject(find.byType(Listener).first);
expect(listener.needsCompositing, isTrue);
await tester.pumpWidget(
Listener(
onPointerEnter: (PointerEnterEvent _) {},
child: const Placeholder(),
),
);
listener = tester.renderObject(find.byType(Listener).first);
expect(listener.needsCompositing, isFalse);
});
testWidgets('works with transform', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/31986.
final Key key = UniqueKey();
const double scaleFactor = 2.0;
const double localWidth = 150.0;
const double localHeight = 100.0;
final List<PointerEvent> events = <PointerEvent>[];
await tester.pumpWidget(
MaterialApp(
home: Center(
child: Transform.scale(
scale: scaleFactor,
child: Listener(
onPointerEnter: (PointerEnterEvent event) {
events.add(event);
},
onPointerHover: (PointerHoverEvent event) {
events.add(event);
},
onPointerExit: (PointerExitEvent event) {
events.add(event);
},
child: Container(
key: key,
color: Colors.blue,
height: localHeight,
width: localWidth,
child: const Text('Hi'),
),
),
),
),
),
);
final Offset topLeft = tester.getTopLeft(find.byKey(key));
final Offset topRight = tester.getTopRight(find.byKey(key));
final Offset bottomLeft = tester.getBottomLeft(find.byKey(key));
expect(topRight.dx - topLeft.dx, scaleFactor * localWidth);
expect(bottomLeft.dy - topLeft.dy, scaleFactor * localHeight);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(topLeft - const Offset(1, 1));
await tester.pump();
expect(events, isEmpty);
await gesture.moveTo(topLeft + const Offset(1, 1));
await tester.pump();
expect(events, hasLength(2));
expect(events.first, isA<PointerEnterEvent>());
expect(events.last, isA<PointerHoverEvent>());
events.clear();
await gesture.moveTo(bottomLeft + const Offset(1, -1));
await tester.pump();
expect(events.single, isA<PointerHoverEvent>());
expect(events.single.delta, const Offset(0.0, scaleFactor * localHeight - 2));
events.clear();
await gesture.moveTo(bottomLeft + const Offset(1, 1));
await tester.pump();
expect(events.single, isA<PointerExitEvent>());
events.clear();
await gesture.removePointer();
});
testWidgets('needsCompositing updates correctly and is respected', (WidgetTester tester) async {
// Pretend that we have a mouse connected.
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await tester.pumpWidget(
Transform.scale(
scale: 2.0,
child: Listener(
onPointerDown: (PointerDownEvent _) { },
),
),
);
final RenderPointerListener listener = tester.renderObject(find.byType(Listener));
expect(listener.needsCompositing, isFalse);
// No TransformLayer for `Transform.scale` is added because composting is
// not required and therefore the transform is executed on the canvas
// directly. (One TransformLayer is always present for the root
// transform.)
expect(tester.layers.whereType<TransformLayer>(), hasLength(1));
await tester.pumpWidget(
Transform.scale(
scale: 2.0,
child: Listener(
onPointerDown: (PointerDownEvent _) { },
onPointerHover: (PointerHoverEvent _) { },
),
),
);
expect(listener.needsCompositing, isTrue);
// Compositing is required, therefore a dedicated TransformLayer for
// `Transform.scale` is added.
expect(tester.layers.whereType<TransformLayer>(), hasLength(2));
await tester.pumpWidget(
Transform.scale(
scale: 2.0,
child: Listener(
onPointerDown: (PointerDownEvent _) { },
),
),
);
expect(listener.needsCompositing, isFalse);
// TransformLayer for `Transform.scale` is removed again as transform is
// executed directly on the canvas.
expect(tester.layers.whereType<TransformLayer>(), hasLength(1));
await gesture.removePointer();
});
testWidgets("Callbacks aren't called during build", (WidgetTester tester) async {
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await tester.pumpWidget(
const Center(child: HoverFeedback()),
);
await gesture.moveTo(tester.getCenter(find.byType(Text)));
await tester.pumpAndSettle();
expect(HoverClientState.numEntries, equals(1));
expect(HoverClientState.numExits, equals(0));
expect(find.text('HOVERING'), findsOneWidget);
await tester.pumpWidget(
Container(),
);
await tester.pump();
expect(HoverClientState.numEntries, equals(1));
expect(HoverClientState.numExits, equals(1));
await tester.pumpWidget(
const Center(child: HoverFeedback()),
);
await tester.pump();
expect(HoverClientState.numEntries, equals(2));
expect(HoverClientState.numExits, equals(1));
await gesture.removePointer();
});
testWidgets("Listener activate/deactivate don't duplicate annotations", (WidgetTester tester) async {
final GlobalKey feedbackKey = GlobalKey();
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await tester.pumpWidget(
Center(child: HoverFeedback(key: feedbackKey)),
);
await gesture.moveTo(tester.getCenter(find.byType(Text)));
await tester.pumpAndSettle();
expect(HoverClientState.numEntries, equals(1));
expect(HoverClientState.numExits, equals(0));
expect(find.text('HOVERING'), findsOneWidget);
await tester.pumpWidget(
Center(child: Container(child: HoverFeedback(key: feedbackKey))),
);
await tester.pump();
expect(HoverClientState.numEntries, equals(2));
expect(HoverClientState.numExits, equals(1));
await tester.pumpWidget(
Container(),
);
await tester.pump();
expect(HoverClientState.numEntries, equals(2));
expect(HoverClientState.numExits, equals(2));
await gesture.removePointer();
});
testWidgets('Exit event when unplugging mouse should have a position', (WidgetTester tester) async {
final List<PointerEnterEvent> enter = <PointerEnterEvent>[];
final List<PointerHoverEvent> hover = <PointerHoverEvent>[];
final List<PointerExitEvent> exit = <PointerExitEvent>[];
await tester.pumpWidget(
Center(
child: Listener(
onPointerEnter: (PointerEnterEvent e) => enter.add(e),
onPointerHover: (PointerHoverEvent e) => hover.add(e),
onPointerExit: (PointerExitEvent e) => exit.add(e),
child: Container(
height: 100.0,
width: 100.0,
),
),
),
);
// Plug-in a mouse and move it to the center of the container.
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byType(Container)));
await tester.pumpAndSettle();
expect(enter.length, 1);
expect(enter.single.position, const Offset(400.0, 300.0));
expect(hover.length, 1);
expect(hover.single.position, const Offset(400.0, 300.0));
expect(exit.length, 0);
enter.clear();
hover.clear();
exit.clear();
// Unplug the mouse.
await gesture.removePointer();
await tester.pumpAndSettle();
expect(enter.length, 0);
expect(hover.length, 0);
expect(exit.length, 1);
expect(exit.single.position, const Offset(400.0, 300.0));
expect(exit.single.delta, const Offset(0.0, 0.0));
});
});
}
......@@ -11,66 +11,6 @@ import 'package:flutter/widgets.dart';
import 'package:flutter/gestures.dart';
class HoverClient extends StatefulWidget {
const HoverClient({Key key, this.onHover, this.child}) : super(key: key);
final ValueChanged<bool> onHover;
final Widget child;
@override
HoverClientState createState() => HoverClientState();
}
class HoverClientState extends State<HoverClient> {
static int numEntries = 0;
static int numExits = 0;
void _onExit(PointerExitEvent details) {
numExits++;
if (widget.onHover != null) {
widget.onHover(false);
}
}
void _onEnter(PointerEnterEvent details) {
numEntries++;
if (widget.onHover != null) {
widget.onHover(true);
}
}
@override
Widget build(BuildContext context) {
return Listener(
onPointerEnter: _onEnter,
onPointerExit: _onExit,
child: widget.child,
);
}
}
class HoverFeedback extends StatefulWidget {
const HoverFeedback({Key key}) : super(key: key);
@override
_HoverFeedbackState createState() => _HoverFeedbackState();
}
class _HoverFeedbackState extends State<HoverFeedback> {
bool _hovering = false;
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: HoverClient(
onHover: (bool hovering) => setState(() => _hovering = hovering),
child: Text(_hovering ? 'HOVERING' : 'not hovering'),
),
);
}
}
void main() {
testWidgets('Events bubble up the tree', (WidgetTester tester) async {
final List<String> log = <String>[];
......@@ -106,544 +46,6 @@ void main() {
]));
});
group('Listener hover detection', () {
setUp((){
HoverClientState.numExits = 0;
HoverClientState.numEntries = 0;
});
testWidgets('detects pointer enter', (WidgetTester tester) async {
PointerEnterEvent enter;
PointerHoverEvent move;
PointerExitEvent exit;
await tester.pumpWidget(Center(
child: Listener(
child: Container(
color: const Color.fromARGB(0xff, 0xff, 0x00, 0x00),
width: 100.0,
height: 100.0,
),
onPointerEnter: (PointerEnterEvent details) => enter = details,
onPointerHover: (PointerHoverEvent details) => move = details,
onPointerExit: (PointerExitEvent details) => exit = details,
),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(const Offset(400.0, 300.0));
await tester.pump();
expect(move, isNotNull);
expect(move.position, equals(const Offset(400.0, 300.0)));
expect(enter, isNotNull);
expect(enter.position, equals(const Offset(400.0, 300.0)));
expect(exit, isNull);
await gesture.removePointer();
});
testWidgets('detects pointer exiting', (WidgetTester tester) async {
PointerEnterEvent enter;
PointerHoverEvent move;
PointerExitEvent exit;
await tester.pumpWidget(Center(
child: Listener(
child: Container(
width: 100.0,
height: 100.0,
),
onPointerEnter: (PointerEnterEvent details) => enter = details,
onPointerHover: (PointerHoverEvent details) => move = details,
onPointerExit: (PointerExitEvent details) => exit = details,
),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(const Offset(400.0, 300.0));
await tester.pump();
move = null;
enter = null;
await gesture.moveTo(const Offset(1.0, 1.0));
await tester.pump();
expect(move, isNull);
expect(enter, isNull);
expect(exit, isNotNull);
expect(exit.position, equals(const Offset(1.0, 1.0)));
await gesture.removePointer();
});
testWidgets('detects pointer exit when widget disappears', (WidgetTester tester) async {
PointerEnterEvent enter;
PointerHoverEvent move;
PointerExitEvent exit;
await tester.pumpWidget(Center(
child: Listener(
child: Container(
width: 100.0,
height: 100.0,
),
onPointerEnter: (PointerEnterEvent details) => enter = details,
onPointerHover: (PointerHoverEvent details) => move = details,
onPointerExit: (PointerExitEvent details) => exit = details,
),
));
final RenderPointerListener renderListener = tester.renderObject(find.byType(Listener));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(const Offset(400.0, 300.0));
await tester.pump();
expect(move, isNotNull);
expect(move.position, equals(const Offset(400.0, 300.0)));
expect(enter, isNotNull);
expect(enter.position, equals(const Offset(400.0, 300.0)));
expect(exit, isNull);
await tester.pumpWidget(Center(
child: Container(
width: 100.0,
height: 100.0,
),
));
expect(exit, isNotNull);
expect(exit.position, equals(const Offset(400.0, 300.0)));
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener.hoverAnnotation), isFalse);
await gesture.removePointer();
});
testWidgets('Hover works with nested listeners', (WidgetTester tester) async {
final UniqueKey key1 = UniqueKey();
final UniqueKey key2 = UniqueKey();
final List<PointerEnterEvent> enter1 = <PointerEnterEvent>[];
final List<PointerHoverEvent> move1 = <PointerHoverEvent>[];
final List<PointerExitEvent> exit1 = <PointerExitEvent>[];
final List<PointerEnterEvent> enter2 = <PointerEnterEvent>[];
final List<PointerHoverEvent> move2 = <PointerHoverEvent>[];
final List<PointerExitEvent> exit2 = <PointerExitEvent>[];
void clearLists() {
enter1.clear();
move1.clear();
exit1.clear();
enter2.clear();
move2.clear();
exit2.clear();
}
await tester.pumpWidget(Container());
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(const Offset(400.0, 0.0));
await tester.pump();
await tester.pumpWidget(
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Listener(
onPointerEnter: (PointerEnterEvent details) => enter1.add(details),
onPointerHover: (PointerHoverEvent details) => move1.add(details),
onPointerExit: (PointerExitEvent details) => exit1.add(details),
key: key1,
child: Container(
width: 200,
height: 200,
padding: const EdgeInsets.all(50.0),
child: Listener(
key: key2,
onPointerEnter: (PointerEnterEvent details) => enter2.add(details),
onPointerHover: (PointerHoverEvent details) => move2.add(details),
onPointerExit: (PointerExitEvent details) => exit2.add(details),
child: Container(),
),
),
),
],
),
);
final RenderPointerListener renderListener1 = tester.renderObject(find.byKey(key1));
final RenderPointerListener renderListener2 = tester.renderObject(find.byKey(key2));
Offset center = tester.getCenter(find.byKey(key2));
await gesture.moveTo(center);
await tester.pump();
expect(move2, isNotEmpty);
expect(enter2, isNotEmpty);
expect(exit2, isEmpty);
expect(move1, isNotEmpty);
expect(move1.last.position, equals(center));
expect(enter1, isNotEmpty);
expect(enter1.last.position, equals(center));
expect(exit1, isEmpty);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener1.hoverAnnotation), isTrue);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener2.hoverAnnotation), isTrue);
clearLists();
// Now make sure that exiting the child only triggers the child exit, not
// the parent too.
center = center - const Offset(75.0, 0.0);
await gesture.moveTo(center);
await tester.pumpAndSettle();
expect(move2, isEmpty);
expect(enter2, isEmpty);
expect(exit2, isNotEmpty);
expect(move1, isNotEmpty);
expect(move1.last.position, equals(center));
expect(enter1, isEmpty);
expect(exit1, isEmpty);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener1.hoverAnnotation), isTrue);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener2.hoverAnnotation), isTrue);
clearLists();
await gesture.removePointer();
});
testWidgets('Hover transfers between two listeners', (WidgetTester tester) async {
final UniqueKey key1 = UniqueKey();
final UniqueKey key2 = UniqueKey();
final List<PointerEnterEvent> enter1 = <PointerEnterEvent>[];
final List<PointerHoverEvent> move1 = <PointerHoverEvent>[];
final List<PointerExitEvent> exit1 = <PointerExitEvent>[];
final List<PointerEnterEvent> enter2 = <PointerEnterEvent>[];
final List<PointerHoverEvent> move2 = <PointerHoverEvent>[];
final List<PointerExitEvent> exit2 = <PointerExitEvent>[];
void clearLists() {
enter1.clear();
move1.clear();
exit1.clear();
enter2.clear();
move2.clear();
exit2.clear();
}
await tester.pumpWidget(Container());
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(const Offset(400.0, 0.0));
await tester.pump();
await tester.pumpWidget(
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Listener(
key: key1,
child: Container(
width: 100.0,
height: 100.0,
),
onPointerEnter: (PointerEnterEvent details) => enter1.add(details),
onPointerHover: (PointerHoverEvent details) => move1.add(details),
onPointerExit: (PointerExitEvent details) => exit1.add(details),
),
Listener(
key: key2,
child: Container(
width: 100.0,
height: 100.0,
),
onPointerEnter: (PointerEnterEvent details) => enter2.add(details),
onPointerHover: (PointerHoverEvent details) => move2.add(details),
onPointerExit: (PointerExitEvent details) => exit2.add(details),
),
],
),
);
final RenderPointerListener renderListener1 = tester.renderObject(find.byKey(key1));
final RenderPointerListener renderListener2 = tester.renderObject(find.byKey(key2));
final Offset center1 = tester.getCenter(find.byKey(key1));
final Offset center2 = tester.getCenter(find.byKey(key2));
await gesture.moveTo(center1);
await tester.pump();
expect(move1, isNotEmpty);
expect(move1.last.position, equals(center1));
expect(enter1, isNotEmpty);
expect(enter1.last.position, equals(center1));
expect(exit1, isEmpty);
expect(move2, isEmpty);
expect(enter2, isEmpty);
expect(exit2, isEmpty);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener1.hoverAnnotation), isTrue);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener2.hoverAnnotation), isTrue);
clearLists();
await gesture.moveTo(center2);
await tester.pump();
expect(move1, isEmpty);
expect(enter1, isEmpty);
expect(exit1, isNotEmpty);
expect(exit1.last.position, equals(center2));
expect(move2, isNotEmpty);
expect(move2.last.position, equals(center2));
expect(enter2, isNotEmpty);
expect(enter2.last.position, equals(center2));
expect(exit2, isEmpty);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener1.hoverAnnotation), isTrue);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener2.hoverAnnotation), isTrue);
clearLists();
await gesture.moveTo(const Offset(400.0, 450.0));
await tester.pump();
expect(move1, isEmpty);
expect(enter1, isEmpty);
expect(exit1, isEmpty);
expect(move2, isEmpty);
expect(enter2, isEmpty);
expect(exit2, isNotEmpty);
expect(exit2.last.position, equals(const Offset(400.0, 450.0)));
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener1.hoverAnnotation), isTrue);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener2.hoverAnnotation), isTrue);
clearLists();
await tester.pumpWidget(Container());
expect(move1, isEmpty);
expect(enter1, isEmpty);
expect(exit1, isEmpty);
expect(move2, isEmpty);
expect(enter2, isEmpty);
expect(exit2, isEmpty);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener1.hoverAnnotation), isFalse);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener2.hoverAnnotation), isFalse);
await gesture.removePointer();
});
testWidgets('needsCompositing set when parent class needsCompositing is set', (WidgetTester tester) async {
await tester.pumpWidget(
Listener(
onPointerEnter: (PointerEnterEvent _) {},
child: const Opacity(opacity: 0.5, child: Placeholder()),
),
);
RenderPointerListener listener = tester.renderObject(find.byType(Listener).first);
expect(listener.needsCompositing, isTrue);
await tester.pumpWidget(
Listener(
onPointerEnter: (PointerEnterEvent _) {},
child: const Placeholder(),
),
);
listener = tester.renderObject(find.byType(Listener).first);
expect(listener.needsCompositing, isFalse);
});
testWidgets('works with transform', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/31986.
final Key key = UniqueKey();
const double scaleFactor = 2.0;
const double localWidth = 150.0;
const double localHeight = 100.0;
final List<PointerEvent> events = <PointerEvent>[];
await tester.pumpWidget(
MaterialApp(
home: Center(
child: Transform.scale(
scale: scaleFactor,
child: Listener(
onPointerEnter: (PointerEnterEvent event) {
events.add(event);
},
onPointerHover: (PointerHoverEvent event) {
events.add(event);
},
onPointerExit: (PointerExitEvent event) {
events.add(event);
},
child: Container(
key: key,
color: Colors.blue,
height: localHeight,
width: localWidth,
child: const Text('Hi'),
),
),
),
),
),
);
final Offset topLeft = tester.getTopLeft(find.byKey(key));
final Offset topRight = tester.getTopRight(find.byKey(key));
final Offset bottomLeft = tester.getBottomLeft(find.byKey(key));
expect(topRight.dx - topLeft.dx, scaleFactor * localWidth);
expect(bottomLeft.dy - topLeft.dy, scaleFactor * localHeight);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(topLeft - const Offset(1, 1));
await tester.pump();
expect(events, isEmpty);
await gesture.moveTo(topLeft + const Offset(1, 1));
await tester.pump();
expect(events, hasLength(2));
expect(events.first, isA<PointerEnterEvent>());
expect(events.last, isA<PointerHoverEvent>());
events.clear();
await gesture.moveTo(bottomLeft + const Offset(1, -1));
await tester.pump();
expect(events.single, isA<PointerHoverEvent>());
expect(events.single.delta, const Offset(0.0, scaleFactor * localHeight - 2));
events.clear();
await gesture.moveTo(bottomLeft + const Offset(1, 1));
await tester.pump();
expect(events.single, isA<PointerExitEvent>());
events.clear();
await gesture.removePointer();
});
testWidgets('needsCompositing updates correctly and is respected', (WidgetTester tester) async {
// Pretend that we have a mouse connected.
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await tester.pumpWidget(
Transform.scale(
scale: 2.0,
child: Listener(
onPointerDown: (PointerDownEvent _) { },
),
),
);
final RenderPointerListener listener = tester.renderObject(find.byType(Listener));
expect(listener.needsCompositing, isFalse);
// No TransformLayer for `Transform.scale` is added because composting is
// not required and therefore the transform is executed on the canvas
// directly. (One TransformLayer is always present for the root
// transform.)
expect(tester.layers.whereType<TransformLayer>(), hasLength(1));
await tester.pumpWidget(
Transform.scale(
scale: 2.0,
child: Listener(
onPointerDown: (PointerDownEvent _) { },
onPointerHover: (PointerHoverEvent _) { },
),
),
);
expect(listener.needsCompositing, isTrue);
// Compositing is required, therefore a dedicated TransformLayer for
// `Transform.scale` is added.
expect(tester.layers.whereType<TransformLayer>(), hasLength(2));
await tester.pumpWidget(
Transform.scale(
scale: 2.0,
child: Listener(
onPointerDown: (PointerDownEvent _) { },
),
),
);
expect(listener.needsCompositing, isFalse);
// TransformLayer for `Transform.scale` is removed again as transform is
// executed directly on the canvas.
expect(tester.layers.whereType<TransformLayer>(), hasLength(1));
await gesture.removePointer();
});
testWidgets("Callbacks aren't called during build", (WidgetTester tester) async {
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await tester.pumpWidget(
const Center(child: HoverFeedback()),
);
await gesture.moveTo(tester.getCenter(find.byType(Text)));
await tester.pumpAndSettle();
expect(HoverClientState.numEntries, equals(1));
expect(HoverClientState.numExits, equals(0));
expect(find.text('HOVERING'), findsOneWidget);
await tester.pumpWidget(
Container(),
);
await tester.pump();
expect(HoverClientState.numEntries, equals(1));
expect(HoverClientState.numExits, equals(1));
await tester.pumpWidget(
const Center(child: HoverFeedback()),
);
await tester.pump();
expect(HoverClientState.numEntries, equals(2));
expect(HoverClientState.numExits, equals(1));
await gesture.removePointer();
});
testWidgets("Listener activate/deactivate don't duplicate annotations", (WidgetTester tester) async {
final GlobalKey feedbackKey = GlobalKey();
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await tester.pumpWidget(
Center(child: HoverFeedback(key: feedbackKey)),
);
await gesture.moveTo(tester.getCenter(find.byType(Text)));
await tester.pumpAndSettle();
expect(HoverClientState.numEntries, equals(1));
expect(HoverClientState.numExits, equals(0));
expect(find.text('HOVERING'), findsOneWidget);
await tester.pumpWidget(
Center(child: Container(child: HoverFeedback(key: feedbackKey))),
);
await tester.pump();
expect(HoverClientState.numEntries, equals(2));
expect(HoverClientState.numExits, equals(1));
await tester.pumpWidget(
Container(),
);
await tester.pump();
expect(HoverClientState.numEntries, equals(2));
expect(HoverClientState.numExits, equals(2));
await gesture.removePointer();
});
testWidgets('Exit event when unplugging mouse should have a position', (WidgetTester tester) async {
final List<PointerEnterEvent> enter = <PointerEnterEvent>[];
final List<PointerHoverEvent> hover = <PointerHoverEvent>[];
final List<PointerExitEvent> exit = <PointerExitEvent>[];
await tester.pumpWidget(
Center(
child: Listener(
onPointerEnter: (PointerEnterEvent e) => enter.add(e),
onPointerHover: (PointerHoverEvent e) => hover.add(e),
onPointerExit: (PointerExitEvent e) => exit.add(e),
child: Container(
height: 100.0,
width: 100.0,
),
),
),
);
// Plug-in a mouse and move it to the center of the container.
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byType(Container)));
await tester.pumpAndSettle();
expect(enter.length, 1);
expect(enter.single.position, const Offset(400.0, 300.0));
expect(hover.length, 1);
expect(hover.single.position, const Offset(400.0, 300.0));
expect(exit.length, 0);
enter.clear();
hover.clear();
exit.clear();
// Unplug the mouse.
await gesture.removePointer();
await tester.pumpAndSettle();
expect(enter.length, 0);
expect(hover.length, 0);
expect(exit.length, 1);
expect(exit.single.position, const Offset(400.0, 300.0));
expect(exit.single.delta, const Offset(0.0, 0.0));
});
});
group('transformed events', () {
testWidgets('simple offset for touch/signal', (WidgetTester tester) async {
final List<PointerEvent> events = <PointerEvent>[];
......
// Copyright 2019 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/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter/gestures.dart';
class HoverClient extends StatefulWidget {
const HoverClient({
Key key,
this.onHover,
this.child,
this.onEnter,
this.onExit,
}) : super(key: key);
final ValueChanged<bool> onHover;
final Widget child;
final VoidCallback onEnter;
final VoidCallback onExit;
@override
HoverClientState createState() => HoverClientState();
}
class HoverClientState extends State<HoverClient> {
void _onExit(PointerExitEvent details) {
if (widget.onExit != null)
widget.onExit();
if (widget.onHover != null) {
widget.onHover(false);
}
}
void _onEnter(PointerEnterEvent details) {
if (widget.onEnter != null)
widget.onEnter();
if (widget.onHover != null) {
widget.onHover(true);
}
}
@override
Widget build(BuildContext context) {
return MouseRegion(
onEnter: _onEnter,
onExit: _onExit,
child: widget.child,
);
}
}
class HoverFeedback extends StatefulWidget {
const HoverFeedback({Key key, this.onEnter, this.onExit}) : super(key: key);
final VoidCallback onEnter;
final VoidCallback onExit;
@override
_HoverFeedbackState createState() => _HoverFeedbackState();
}
class _HoverFeedbackState extends State<HoverFeedback> {
bool _hovering = false;
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: HoverClient(
onHover: (bool hovering) => setState(() => _hovering = hovering),
onEnter: widget.onEnter,
onExit: widget.onExit,
child: Text(_hovering ? 'HOVERING' : 'not hovering'),
),
);
}
}
void main() {
group('MouseRegion hover detection', () {
testWidgets('detects pointer enter', (WidgetTester tester) async {
PointerEnterEvent enter;
PointerHoverEvent move;
PointerExitEvent exit;
await tester.pumpWidget(Center(
child: MouseRegion(
child: Container(
color: const Color.fromARGB(0xff, 0xff, 0x00, 0x00),
width: 100.0,
height: 100.0,
),
onEnter: (PointerEnterEvent details) => enter = details,
onHover: (PointerHoverEvent details) => move = details,
onExit: (PointerExitEvent details) => exit = details,
),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(const Offset(400.0, 300.0));
await tester.pump();
expect(move, isNotNull);
expect(move.position, equals(const Offset(400.0, 300.0)));
expect(enter, isNotNull);
expect(enter.position, equals(const Offset(400.0, 300.0)));
expect(exit, isNull);
await gesture.removePointer();
});
testWidgets('detects pointer exiting', (WidgetTester tester) async {
PointerEnterEvent enter;
PointerHoverEvent move;
PointerExitEvent exit;
await tester.pumpWidget(Center(
child: MouseRegion(
child: Container(
width: 100.0,
height: 100.0,
),
onEnter: (PointerEnterEvent details) => enter = details,
onHover: (PointerHoverEvent details) => move = details,
onExit: (PointerExitEvent details) => exit = details,
),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(const Offset(400.0, 300.0));
await tester.pump();
move = null;
enter = null;
await gesture.moveTo(const Offset(1.0, 1.0));
await tester.pump();
expect(move, isNull);
expect(enter, isNull);
expect(exit, isNotNull);
expect(exit.position, equals(const Offset(1.0, 1.0)));
await gesture.removePointer();
});
testWidgets('detects pointer exit when widget disappears', (WidgetTester tester) async {
PointerEnterEvent enter;
PointerHoverEvent move;
PointerExitEvent exit;
await tester.pumpWidget(Center(
child: MouseRegion(
child: Container(
width: 100.0,
height: 100.0,
),
onEnter: (PointerEnterEvent details) => enter = details,
onHover: (PointerHoverEvent details) => move = details,
onExit: (PointerExitEvent details) => exit = details,
),
));
final RenderMouseRegion renderListener = tester.renderObject(find.byType(MouseRegion));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(const Offset(400.0, 300.0));
await tester.pump();
expect(move, isNotNull);
expect(move.position, equals(const Offset(400.0, 300.0)));
expect(enter, isNotNull);
expect(enter.position, equals(const Offset(400.0, 300.0)));
expect(exit, isNull);
await tester.pumpWidget(Center(
child: Container(
width: 100.0,
height: 100.0,
),
));
expect(exit, isNotNull);
expect(exit.position, equals(const Offset(400.0, 300.0)));
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener.hoverAnnotation), isFalse);
await gesture.removePointer();
});
testWidgets('Hover works with nested listeners', (WidgetTester tester) async {
final UniqueKey key1 = UniqueKey();
final UniqueKey key2 = UniqueKey();
final List<PointerEnterEvent> enter1 = <PointerEnterEvent>[];
final List<PointerHoverEvent> move1 = <PointerHoverEvent>[];
final List<PointerExitEvent> exit1 = <PointerExitEvent>[];
final List<PointerEnterEvent> enter2 = <PointerEnterEvent>[];
final List<PointerHoverEvent> move2 = <PointerHoverEvent>[];
final List<PointerExitEvent> exit2 = <PointerExitEvent>[];
void clearLists() {
enter1.clear();
move1.clear();
exit1.clear();
enter2.clear();
move2.clear();
exit2.clear();
}
await tester.pumpWidget(Container());
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(const Offset(400.0, 0.0));
await tester.pump();
await tester.pumpWidget(
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
MouseRegion(
onEnter: (PointerEnterEvent details) => enter1.add(details),
onHover: (PointerHoverEvent details) => move1.add(details),
onExit: (PointerExitEvent details) => exit1.add(details),
key: key1,
child: Container(
width: 200,
height: 200,
padding: const EdgeInsets.all(50.0),
child: MouseRegion(
key: key2,
onEnter: (PointerEnterEvent details) => enter2.add(details),
onHover: (PointerHoverEvent details) => move2.add(details),
onExit: (PointerExitEvent details) => exit2.add(details),
child: Container(),
),
),
),
],
),
);
final RenderMouseRegion renderListener1 = tester.renderObject(find.byKey(key1));
final RenderMouseRegion renderListener2 = tester.renderObject(find.byKey(key2));
Offset center = tester.getCenter(find.byKey(key2));
await gesture.moveTo(center);
await tester.pump();
expect(move2, isNotEmpty);
expect(enter2, isNotEmpty);
expect(exit2, isEmpty);
expect(move1, isNotEmpty);
expect(move1.last.position, equals(center));
expect(enter1, isNotEmpty);
expect(enter1.last.position, equals(center));
expect(exit1, isEmpty);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener1.hoverAnnotation), isTrue);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener2.hoverAnnotation), isTrue);
clearLists();
// Now make sure that exiting the child only triggers the child exit, not
// the parent too.
center = center - const Offset(75.0, 0.0);
await gesture.moveTo(center);
await tester.pumpAndSettle();
expect(move2, isEmpty);
expect(enter2, isEmpty);
expect(exit2, isNotEmpty);
expect(move1, isNotEmpty);
expect(move1.last.position, equals(center));
expect(enter1, isEmpty);
expect(exit1, isEmpty);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener1.hoverAnnotation), isTrue);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener2.hoverAnnotation), isTrue);
clearLists();
await gesture.removePointer();
});
testWidgets('Hover transfers between two listeners', (WidgetTester tester) async {
final UniqueKey key1 = UniqueKey();
final UniqueKey key2 = UniqueKey();
final List<PointerEnterEvent> enter1 = <PointerEnterEvent>[];
final List<PointerHoverEvent> move1 = <PointerHoverEvent>[];
final List<PointerExitEvent> exit1 = <PointerExitEvent>[];
final List<PointerEnterEvent> enter2 = <PointerEnterEvent>[];
final List<PointerHoverEvent> move2 = <PointerHoverEvent>[];
final List<PointerExitEvent> exit2 = <PointerExitEvent>[];
void clearLists() {
enter1.clear();
move1.clear();
exit1.clear();
enter2.clear();
move2.clear();
exit2.clear();
}
await tester.pumpWidget(Container());
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(const Offset(400.0, 0.0));
await tester.pump();
await tester.pumpWidget(
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
MouseRegion(
key: key1,
child: Container(
width: 100.0,
height: 100.0,
),
onEnter: (PointerEnterEvent details) => enter1.add(details),
onHover: (PointerHoverEvent details) => move1.add(details),
onExit: (PointerExitEvent details) => exit1.add(details),
),
MouseRegion(
key: key2,
child: Container(
width: 100.0,
height: 100.0,
),
onEnter: (PointerEnterEvent details) => enter2.add(details),
onHover: (PointerHoverEvent details) => move2.add(details),
onExit: (PointerExitEvent details) => exit2.add(details),
),
],
),
);
final RenderMouseRegion renderListener1 = tester.renderObject(find.byKey(key1));
final RenderMouseRegion renderListener2 = tester.renderObject(find.byKey(key2));
final Offset center1 = tester.getCenter(find.byKey(key1));
final Offset center2 = tester.getCenter(find.byKey(key2));
await gesture.moveTo(center1);
await tester.pump();
expect(move1, isNotEmpty);
expect(move1.last.position, equals(center1));
expect(enter1, isNotEmpty);
expect(enter1.last.position, equals(center1));
expect(exit1, isEmpty);
expect(move2, isEmpty);
expect(enter2, isEmpty);
expect(exit2, isEmpty);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener1.hoverAnnotation), isTrue);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener2.hoverAnnotation), isTrue);
clearLists();
await gesture.moveTo(center2);
await tester.pump();
expect(move1, isEmpty);
expect(enter1, isEmpty);
expect(exit1, isNotEmpty);
expect(exit1.last.position, equals(center2));
expect(move2, isNotEmpty);
expect(move2.last.position, equals(center2));
expect(enter2, isNotEmpty);
expect(enter2.last.position, equals(center2));
expect(exit2, isEmpty);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener1.hoverAnnotation), isTrue);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener2.hoverAnnotation), isTrue);
clearLists();
await gesture.moveTo(const Offset(400.0, 450.0));
await tester.pump();
expect(move1, isEmpty);
expect(enter1, isEmpty);
expect(exit1, isEmpty);
expect(move2, isEmpty);
expect(enter2, isEmpty);
expect(exit2, isNotEmpty);
expect(exit2.last.position, equals(const Offset(400.0, 450.0)));
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener1.hoverAnnotation), isTrue);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener2.hoverAnnotation), isTrue);
clearLists();
await tester.pumpWidget(Container());
expect(move1, isEmpty);
expect(enter1, isEmpty);
expect(exit1, isEmpty);
expect(move2, isEmpty);
expect(enter2, isEmpty);
expect(exit2, isEmpty);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener1.hoverAnnotation), isFalse);
expect(tester.binding.mouseTracker.isAnnotationAttached(renderListener2.hoverAnnotation), isFalse);
await gesture.removePointer();
});
testWidgets('needsCompositing set when parent class needsCompositing is set', (WidgetTester tester) async {
await tester.pumpWidget(
MouseRegion(
onEnter: (PointerEnterEvent _) {},
child: const Opacity(opacity: 0.5, child: Placeholder()),
),
);
RenderMouseRegion listener = tester.renderObject(find.byType(MouseRegion).first);
expect(listener.needsCompositing, isTrue);
await tester.pumpWidget(
MouseRegion(
onEnter: (PointerEnterEvent _) {},
child: const Placeholder(),
),
);
listener = tester.renderObject(find.byType(MouseRegion).first);
expect(listener.needsCompositing, isFalse);
});
testWidgets('works with transform', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/31986.
final Key key = UniqueKey();
const double scaleFactor = 2.0;
const double localWidth = 150.0;
const double localHeight = 100.0;
final List<PointerEvent> events = <PointerEvent>[];
await tester.pumpWidget(
MaterialApp(
home: Center(
child: Transform.scale(
scale: scaleFactor,
child: MouseRegion(
onEnter: (PointerEnterEvent event) {
events.add(event);
},
onHover: (PointerHoverEvent event) {
events.add(event);
},
onExit: (PointerExitEvent event) {
events.add(event);
},
child: Container(
key: key,
color: Colors.blue,
height: localHeight,
width: localWidth,
child: const Text('Hi'),
),
),
),
),
),
);
final Offset topLeft = tester.getTopLeft(find.byKey(key));
final Offset topRight = tester.getTopRight(find.byKey(key));
final Offset bottomLeft = tester.getBottomLeft(find.byKey(key));
expect(topRight.dx - topLeft.dx, scaleFactor * localWidth);
expect(bottomLeft.dy - topLeft.dy, scaleFactor * localHeight);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(topLeft - const Offset(1, 1));
await tester.pump();
expect(events, isEmpty);
await gesture.moveTo(topLeft + const Offset(1, 1));
await tester.pump();
expect(events, hasLength(2));
expect(events.first, isA<PointerEnterEvent>());
expect(events.last, isA<PointerHoverEvent>());
events.clear();
await gesture.moveTo(bottomLeft + const Offset(1, -1));
await tester.pump();
expect(events.single, isA<PointerHoverEvent>());
expect(events.single.delta, const Offset(0.0, scaleFactor * localHeight - 2));
events.clear();
await gesture.moveTo(bottomLeft + const Offset(1, 1));
await tester.pump();
expect(events.single, isA<PointerExitEvent>());
events.clear();
await gesture.removePointer();
});
testWidgets('needsCompositing updates correctly and is respected', (WidgetTester tester) async {
// Pretend that we have a mouse connected.
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await tester.pumpWidget(
Transform.scale(
scale: 2.0,
child: const MouseRegion(),
),
);
final RenderMouseRegion listener = tester.renderObject(find.byType(MouseRegion));
expect(listener.needsCompositing, isFalse);
// No TransformLayer for `Transform.scale` is added because composting is
// not required and therefore the transform is executed on the canvas
// directly. (One TransformLayer is always present for the root
// transform.)
expect(tester.layers.whereType<TransformLayer>(), hasLength(1));
await tester.pumpWidget(
Transform.scale(
scale: 2.0,
child: MouseRegion(
onHover: (PointerHoverEvent _) { },
),
),
);
expect(listener.needsCompositing, isTrue);
// Compositing is required, therefore a dedicated TransformLayer for
// `Transform.scale` is added.
expect(tester.layers.whereType<TransformLayer>(), hasLength(2));
await tester.pumpWidget(
Transform.scale(
scale: 2.0,
child: const MouseRegion(
),
),
);
expect(listener.needsCompositing, isFalse);
// TransformLayer for `Transform.scale` is removed again as transform is
// executed directly on the canvas.
expect(tester.layers.whereType<TransformLayer>(), hasLength(1));
await gesture.removePointer();
});
testWidgets("Callbacks aren't called during build", (WidgetTester tester) async {
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
int numEntries = 0;
int numExits = 0;
await tester.pumpWidget(
Center(child: HoverFeedback(
onEnter: () => numEntries++,
onExit: () => numExits++,
)),
);
await gesture.moveTo(tester.getCenter(find.byType(Text)));
await tester.pumpAndSettle();
expect(numEntries, equals(1));
expect(numExits, equals(0));
expect(find.text('HOVERING'), findsOneWidget);
await tester.pumpWidget(
Container(),
);
await tester.pump();
expect(numEntries, equals(1));
expect(numExits, equals(1));
await tester.pumpWidget(
Center(child: HoverFeedback(
onEnter: () => numEntries++,
onExit: () => numExits++,
)),
);
await tester.pump();
expect(numEntries, equals(2));
expect(numExits, equals(1));
await gesture.removePointer();
});
testWidgets("MouseRegion activate/deactivate don't duplicate annotations", (WidgetTester tester) async {
final GlobalKey feedbackKey = GlobalKey();
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
int numEntries = 0;
int numExits = 0;
await tester.pumpWidget(
Center(child: HoverFeedback(
key: feedbackKey,
onEnter: () => numEntries++,
onExit: () => numExits++,
)),
);
await gesture.moveTo(tester.getCenter(find.byType(Text)));
await tester.pumpAndSettle();
expect(numEntries, equals(1));
expect(numExits, equals(0));
expect(find.text('HOVERING'), findsOneWidget);
await tester.pumpWidget(
Center(child: Container(child: HoverFeedback(
key: feedbackKey,
onEnter: () => numEntries++,
onExit: () => numExits++,
))),
);
await tester.pump();
expect(numEntries, equals(2));
expect(numExits, equals(1));
await tester.pumpWidget(
Container(),
);
await tester.pump();
expect(numEntries, equals(2));
expect(numExits, equals(2));
await gesture.removePointer();
});
testWidgets('Exit event when unplugging mouse should have a position', (WidgetTester tester) async {
final List<PointerEnterEvent> enter = <PointerEnterEvent>[];
final List<PointerHoverEvent> hover = <PointerHoverEvent>[];
final List<PointerExitEvent> exit = <PointerExitEvent>[];
await tester.pumpWidget(
Center(
child: MouseRegion(
onEnter: (PointerEnterEvent e) => enter.add(e),
onHover: (PointerHoverEvent e) => hover.add(e),
onExit: (PointerExitEvent e) => exit.add(e),
child: Container(
height: 100.0,
width: 100.0,
),
),
),
);
// Plug-in a mouse and move it to the center of the container.
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byType(Container)));
await tester.pumpAndSettle();
expect(enter.length, 1);
expect(enter.single.position, const Offset(400.0, 300.0));
expect(hover.length, 1);
expect(hover.single.position, const Offset(400.0, 300.0));
expect(exit.length, 0);
enter.clear();
hover.clear();
exit.clear();
// Unplug the mouse.
await gesture.removePointer();
await tester.pumpAndSettle();
expect(enter.length, 0);
expect(hover.length, 0);
expect(exit.length, 1);
expect(exit.single.position, const Offset(400.0, 300.0));
expect(exit.single.delta, const Offset(0.0, 0.0));
});
});
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment