如何在Flutter中隐藏鼠标光标?

nc1teljy  于 2023-01-02  发布在  Flutter
关注(0)|答案(1)|浏览(253)
class ExampleWidget extends StatefulWidget {
  const ExampleWidget({Key? key}) : super(key: key);

  @override
  State<ExampleWidget> createState() => _ExampleState();
}

class _ExampleState extends State<ExampleWidget> {
  bool showCursor = false;
  
  @override
  Widget build(BuildContext context) {
    return MouseRegion(
      cursor: showCursor ? SystemMouseCursors.basic : SystemMouseCursors.none,
    );
  }
}

在上面的代码中,在Windows上,如果showCursor设置为false,并且用户移动光标,则鼠标光标将被隐藏。如果showCursor的值设置为false,而用户没有移动鼠标,则光标图标将不会更新,直到用户移动它。
这是由于Flutter引擎中的一个错误:https://github.com/flutter/flutter/issues/76622.
我该如何解决这个问题?有没有其他方法可以在Flutter中隐藏鼠标光标?

qybjjes1

qybjjes11#

我已经找到了解决此问题的方法:

import 'package:win32/win32.dart';
import 'package:win32/win32.dart' as win32;
import 'dart:ffi';
import 'package:ffi/ffi.dart';

Timer(const Duration(milliseconds: 100), () {
    Pointer<POINT> point = malloc();
    win32.GetCursorPos(point);
    win32.SetCursorPos(point.ref.x, point.ref.y);
    free(point);
});

更改cursor后调用此函数即可。
这段代码将调用一个win32 API来手动更新鼠标位置(这将触发光标图标的变化),我还将它 Package 在一个Timer中,这样MouseRegion就有时间做出React。
您可能需要安装win32ffi pub包。
我还创建了一个EnhancedMouseRegion,它的工作原理与MouseRegion相同,但已修复此问题:

import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:win32/win32.dart';
import 'package:win32/win32.dart' as win32;
import 'dart:ffi';
import 'package:ffi/ffi.dart';

class EnhancedMouseRegion extends StatefulWidget {
  final Function(PointerEnterEvent)? onEnter;
  final Function(PointerExitEvent)? onExit;
  final Function(PointerHoverEvent)? onHover;
  final MouseCursor cursor;
  final bool opaque;
  final HitTestBehavior? hitTestBehavior;
  final Widget? child;

  const EnhancedMouseRegion({
    super.key,
    this.onEnter,
    this.onExit,
    this.onHover,
    this.cursor = MouseCursor.defer,
    this.opaque = true,
    this.hitTestBehavior,
    this.child,
  });

  @override
  State<EnhancedMouseRegion> createState() => _EnhancedMouseRegionState();
}

class _EnhancedMouseRegionState extends State<EnhancedMouseRegion> {
  MouseCursor? lastCursor;
  
  @override
  Widget build(BuildContext context) {
    if (lastCursor != widget.cursor) {
      Timer(const Duration(milliseconds: 100), () {
        Pointer<POINT> point = malloc();
        win32.GetCursorPos(point);
        win32.SetCursorPos(point.ref.x, point.ref.y);
        free(point);
      });
    }
    lastCursor = widget.cursor;
    
    return MouseRegion(
      onEnter: widget.onEnter,
      onExit: widget.onExit,
      onHover: widget.onHover,
      cursor: widget.cursor,
      opaque: widget.opaque,
      hitTestBehavior: widget.hitTestBehavior,
      child: widget.child,
    );
  }
}

相关问题