Complete Flutter Project Solutions

How to useimplement Listener Class in Flutter

How to use/implement Listener Class in Flutter?

Introduction:

A widget called the Listener triggers callbacks in response to frequent pointer events.
It pays attention to things like when the cursor is pressed, moved, released, or canceled that can create motions.

It doesn’t pay attention to mouse-specific events as when the mouse arrives, leaves, or hovers over an area without clicking any buttons. Use MouseRegion Class for these events.

When comparing the list of objects that a mouse pointer is hovering on between this frame and the previous frame, MouseRegion is used. This includes moving mouse cursors, starting events, and ending events.

Use Listener or, preferably, GestureDetector Class to listen to common pointer occurrences.

In this article, we will see how to use the listener class in the Flutter app development.

Below is the constructor of the Lister Class.

	
	Listener(
{Key? key,
PointerDownEventListener? onPointerDown,
PointerMoveEventListener? onPointerMove,
PointerUpEventListener? onPointerUp,
PointerHoverEventListener? onPointerHover,
PointerCancelEventListener? onPointerCancel,
PointerSignalEventListener? onPointerSignal,
HitTestBehavior behavior = HitTestBehavior.deferToChild,
Widget? child}
)

Properties of the Listener class:

PointerDownEventListener? onPointerDown:
Callers can be informed of these events in a widget tree thanks to the listener.onPointerDown function.

PointerMoveEventListener? onPointerMove:
While the pointer is in contact with the object, it has moved in relation to that object.

PointerUpEventListener? onPointerUp:
The pointer is no longer in close proximity to the object.

PointerHoverEventListener? onPointerHover:
While the pointer is not in contact with the device, it has moved in relation to it.

PointerCancelEventListener? onPointerCancel:
The input from the pointer is no longer directed towards this receiver.

PointerSignalEventListener? onPointerSignal:
Pointer signals are discrete events that come from the pointer but don’t affect the state of the pointer itself. They don’t have to be understood in the context of a chain of events to be understood.

HitTestBehavior behavior:
Only if one of their children is struck by the hit test do targets that defer to their children get events within their boundaries.

Widget? child:
The Flutter framework’s primary class hierarchy is constructed of widgets. An immutable description of a component of a user interface is referred to as a widget. Elements that govern the underlying render tree can be created by inflating widgets.

Example of Listener Class:

	
import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text("Flutter Listener Class Sample")),
        body: const Center(
          child: MyStatefulWidget(),
        ),
      ),
    );
  }
}
class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key? key}) : super(key: key);
  @override
  State createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State {
  int _down = 0;
  int _up = 0;
  double x = 0.0;
  double y = 0.0;
  void _incrementDown(PointerEvent details) {
    _updateLocation(details);
    setState(() {
      _down++;
    });
  }
  void _incrementUp(PointerEvent details) {
    _updateLocation(details);
    setState(() {
      _up++;
    });
  }
  void _updateLocation(PointerEvent details) {
    setState(() {
      x = details.position.dx;
      y = details.position.dy;
    });
  }
  @override
  Widget build(BuildContext context) {
    return ConstrainedBox(
      constraints: BoxConstraints.tight(const Size(400.0, 300.0)),
      child: Listener(
        onPointerDown: _incrementDown,
        onPointerMove: _updateLocation,
        onPointerUp: _incrementUp,
        child: Container(
          color: Colors.green,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Text(
                  'You have pressed or released in this area this many times:'),
              Text(
                '$_down presses\n$_up releases',
                style: Theme.of(context).textTheme.headline4,
              ),
              Text(
                'The cursor is here: (${x.toStringAsFixed(2)}, ${y.toStringAsFixed(2)})',
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Output:

useimplement Listener Class Final Output
useimplement Listener Class Final Output

Conclusion:

We described the fundamental implementation of the Listener in a Flutter in the article; you are free to change the code as you see fit. This was a brief explanation of Listener On User Interaction from our perspective, and it functions with Flutter. Get experienced consultation support from our Flutter developer for custom business mobile application development solutions. Hope you enjoy this article.

Frequently Asked Questions (FAQs)

1. What Is the MouseRegion widget in Flutter?

MouseRegion is the one type of widget which is utilized to track all the movements of the mouse. It is preferred when we have a particular portion on the device’s screen where we require interaction that is being noticed by the gadget to execute various callbacks.

2. What is the listener class in Flutter?

A widget calls a callback in response to the regular pointer events. It will listen to the events that can be created gestures, like when the pointer is pressed, moved, released, or canceled.

3. Define Gestures in the development of Flutter

Gestures are the best way to interact with the mobile application. It can be defined as the user’s physical movement with the intention of activating a particular control on the smart gadget. Gestures are as simple as tapping the mobile device’s screen to the complicated actions used in gaming applications.

Request a Quote