MouseRegion introduction
In our H5 development, we all know that CSS has a hover to change the style of an element, so we can also monitor the entry and exit of the mouse in a Flutter area by MouseRegion.
Video Tutorial Address
Gesture series video tutorial address
When to use MouseRegion?
MouseRegion is commonly used in Flutter Web development or desktop applications. MouseRegion is used when the mouse needs to add specific functions to a component that enters or exits.
Constructor of MouseRegion
const MouseRegion({
Key? key,
this.onEnter,
this.onExit,
this.onHover,
this.cursor = MouseCursor.defer,
this.opaque = true.this.child,
}) : assert(cursor ! =null),
assert(opaque ! =null),
super(key: key);
Copy the code
MouseRegion properties and description
There are six attributes
field | attribute | describe |
---|---|---|
onEnter | PointerEnterEventListener | The callback when the mouse enters the area |
onExit | PointerHoverEventListener | A callback when the mouse exits the area |
onHover | PointerExitEventListener | A callback when the mouse moves over an area |
cursor | MouseCursor | The style of the cursor when hovering over the area |
opaque | bool | Whether to block detection mouse |
child | Widget | Child components |
Basic use of MouseRegion
We wrap a child Container with MouseRegion, which goes through the onEnter callback and changes its color to green when the mouse moves, goes through the onHover callback when the mouse exits the Container area and enters the onExit callback and changes its color to orange. The code is as follows:
import 'package:flutter/material.dart';
class MouseRegionExample extends StatefulWidget {
@override
_MouseRegionExampleState createState() => _MouseRegionExampleState();
}
class _MouseRegionExampleState extends State<MouseRegionExample> {
Color _color = Colors.orange;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("MouseRegion"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
MouseRegion(
onEnter: (event) {
print("onEnter---$event");
setState(() {
_color = Colors.green;
});
},
onExit: (event) {
print("onExit---$event");
setState(() {
_color = Colors.orange;
});
},
onHover: (event) {
// print("onHover---$event");
},
// cursor: MouseCursor.uncontrolled,
cursor: SystemMouseCursors.click,
opaque: false,
child: Container(
width: 100,
height: 100, color: _color, ), ), ], ) ), ); }}Copy the code
MouseRegion effect display
conclusion
MouseRegion is specifically designed for Web and desktop applications to monitor mouse events in a certain area, including mouse entry and exit and movement trajectory. MouseRegion is rarely used in normal development, but will be frequently used in future Flutter Web development.