User interaction is a crucial aspect of any Flutter application, and it's essential to consider both touch and mouse inputs for a seamless experience across different platforms. The MouseRegion widget in Flutter provides a way to handle mouse-specific interactions, allowing you to enhance your application's responsiveness and user engagement. In this blog post, we'll explore the MouseRegion widget, its key attributes, and provide a comprehensive example to demonstrate its usage.
MouseRegion is a Flutter widget designed to handle mouse-specific interactions, such as hovering and entering. It allows developers to create responsive UIs that adapt to different input devices, providing a consistent experience for both mouse and touch users.
Attributes of MouseRegion:
child (required):
- The widget to which the mouse-related behaviors will be applied.
cursor:
- Defines the mouse cursor to be displayed when the pointer is over the region.
onEnter:
- A callback function that is triggered when the mouse pointer enters the region.
onExit:
- A callback function that is triggered when the mouse pointer exits the region.
onHover:
- A callback function that is triggered continuously while the mouse pointer is within the region.
Example:
// main.dart
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'MouseRegion Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('MouseRegion Example'),
),
body: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
// First Container with MouseRegion
MouseRegion(
cursor: SystemMouseCursors.click,
onEnter: (_) {
print('Mouse entered Container 1');
},
onExit: (_) {
print('Mouse exited Container 1');
},
child: Container(
width: 150,
height: 150,
color: Colors.blue,
child: Center(
child: Text('Container 1'),
),
),
),
// Second Container with MouseRegion
MouseRegion(
cursor: SystemMouseCursors.click,
onEnter: (_) {
print('Mouse entered Container 2');
},
onExit: (_) {
print('Mouse exited Container 2');
},
child: Container(
width: 150,
height: 150,
color: Colors.green,
child: Center(
child: Text('Container 2'),
),
),
),
],
),
),
);
}
}