Mouse Events - wurzelsand/flutter-memos GitHub Wiki

Mouse Events

Das gesamte Fenster soll Mausereignisse registrieren.

Ausführung

import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';

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

class ExampleApp extends StatelessWidget {
  const ExampleApp({super.key});

  @override
  Widget build(BuildContext context) => const MaterialApp(
    home: Scaffold(
      body: ExampleWidget(),
    ),
  );
}

class ExampleWidget extends StatefulWidget {
  const ExampleWidget({super.key});

  @override
  State createState() => _ExampleWidget();
}

class _ExampleWidget extends State<ExampleWidget> {
  Offset pointerPosition = Offset.zero;
  int numberOfClicks = 0;
  int scrollY = 0;

  @override
  Widget build(BuildContext context) {
    return Listener(
        onPointerSignal: (pointerSignalEvent) {
          setState(() {
            if (pointerSignalEvent is PointerScrollEvent) {
              scrollY = pointerSignalEvent.scrollDelta.dy.round();
            }
          });
        },
        onPointerMove: (pointerMoveEvent) { // only if pointer down
          setState(() {
            pointerPosition = pointerMoveEvent.position;
          });
        },
        onPointerUp: (pointerUpEvent) {
          setState(() {
            numberOfClicks++;
          });
        },
        child: Container(
            color: Colors.green,
            constraints: const BoxConstraints.expand(),
            child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('Position: ${pointerPosition.dx.round()}, ${pointerPosition.dy.round()}'),
                  Text('Vertical Scroll: $scrollY'),
                  Text('Clicks: $numberOfClicks'),
                ]
            )
        )
    );
  }
}