Flutter 可以检测悬停的手写笔吗?

Gui*_*ira 7 android flutter

一些手机,尤其是三星 Galaxy Note 系列设备,配备了触控笔(触控笔?),当它们靠近屏幕但​​不接触屏幕时可以被检测到。Flutter 可以检测和处理这种事件吗?

(以下是我对此的调查,如果您已经知道答案,请跳过此部分)

监听器类可以检测当触摸屏幕和手写笔执行的操作MouseRegion类应该检测的动作与盘旋指针进行。所以我写了这个简单的小部件来测试这两个类:

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String  _message = "Nothing happened";
  String _location = "Nothing happened";

  void onEnter(PointerEnterEvent event) {
    setState(() {
      _message = "Pointer entered";
    });
  }

  void onExit(PointerExitEvent event) {
    setState(() {
      _message = "Pointer exited";
    });
  }

  void onHover(PointerHoverEvent event) {
    setState(() {
      _location = "Pointer at ${event.localPosition.dx} ${event.localPosition.dy} distance ${event.distance}";
    });
  }

  void onDown(PointerDownEvent event) {
    setState(() {
      _message = "Pointer down";
    });
  }

  void onUp(PointerUpEvent event) {
    setState(() {
      _message = "Pointer up";
    });
  }

  void onMove(PointerMoveEvent event) {
    setState(() {
      _location = "Pointer moving at ${event.localPosition.dx} ${event.localPosition.dy} pressure ${event.pressure}";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          children: [
            MouseRegion(
              onEnter: onEnter,
              onExit: onExit,
              onHover: onHover,
              child: Listener(
                  onPointerDown: onDown,
                  onPointerUp: onUp,
                  onPointerMove: onMove,
                  child: Container(
                      width: 500,
                      height: 500,
                      color: Colors.red
                  )
              )
            ),
            Text(_message),
            Text(_location)
          ]
        )
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

使用蓝牙鼠标,当我将指针移到该区域上时,MouseRegion小部件会发出事件,但是当我使用手写笔执行相同操作时,没有任何反应。

但是,Listener当我用手写笔触摸该区域时,该类确实会发出事件,并且事件实例甚至包括特定于手写笔的信息,例如压力。该PointerEvent类甚至还包括一个distance场,并根据其描述,它应该是表示从指针到屏幕上,这似乎正是我要找的要素的距离。

这条评论表明 Flutter “还没有准备好”支持可悬停的触控笔,但他似乎并不完全确定它是在一年前发布的,所以也许有些事情发生了变化。

最后,当我在运行应用程序时将触控笔悬停在屏幕上时,Android Studio 的控制台上会显示以下消息:

D/ViewRootImpl(16531): updatePointerIcon pointerType = 20001, calling pid = 16531
D/InputManager(16531): setPointerIconType iconId = 20001, callingPid = 16531
Run Code Online (Sandbox Code Playgroud)

所以它似乎确实检测到了一些东西。在我看来,Flutter 正在积极地丢弃与触控笔相关的事件,并且只处理鼠标事件,因为在本机端,鼠标和笔操作都可以由MotionEvent类处理。

我错过了什么吗?是否有其他类能够处理这种事件?或者在某处进行一些设置以启用它?还是目前真的不可能?

Gui*_*ira 6

我希望十分钟后有人会来到这里说“哦,你可以使用这个类,你不知道如何使用谷歌吗?”但显然情况并非如此。所以我决定研究一下 Flutter 的源代码。

所以我从MouseRegion类开始,它使用_RawMouseRegion,它使用RenderMouseRegion。然后,它使用MouseTrackerAnnotation注册一些事件处理回调。该类的实例由MouseTracker拾取,它接收指针事件并调用所有对它们感兴趣的回调。这是在_handleEvent函数中完成的,它的前两行是:

if (event.kind != PointerDeviceKind.mouse)
      return;
Run Code Online (Sandbox Code Playgroud)

所以我想我找到了罪魁祸首。这可能可以通过简单地添加PointerDeviceKind.stylus到该if语句来解决。或者也许这样做会使地球开始向后旋转或其他什么。GitHub 问题可能是获得答案的最佳地点。

但并不是所有的都丢失了。该MouseTracker班获得从它的事件PointerRouter,它的单个实例可在GestureBinding.instance.pointerRouter。该PointerRouter有一个addGlobalRoute,让您注册自己的回调接收事件的方法和包括手写笔事件MouseTracker被忽略。

我确定这不是推荐的做事方式,因为它绕过了 Flutter 的许多内部内容,而这些内容可能是有原因的。但是,虽然没有“官方”的做事方式(我怀疑这个非常具体的用例远不及他们的优先事项列表的顶部),但可以通过这种方式解决它。嘿,我什至发现了一个直接使用 的常规小部件PointerRouter,所以它可能不太危险。

这个事件PointerRouter给你带来的不像 from 那样方便MouseRegion,因为它的位置是在全局坐标中。但是您可以获取RenderBox小部件的 并用于globalToLocal将位置转换为本地坐标。这是一个小的工作示例:

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  //We'll use the render box of the object with this key to transform the event coordinates:
  GlobalKey _containerKey = GlobalKey();
  //Store the render box:
  //(The method to find the render box starts with "find" so I suspect it is doing
  //some non trivial amount of work, so instead of calling it on every event, I'll
  //just store the renderbox here):
  RenderBox _rb;
  String  _message = "Nothing happened";

  _MyHomePageState() {
    //Register a method to receive the pointer events:
    GestureBinding.instance.pointerRouter.addGlobalRoute(_handleEvent);
  }

  @override
  void dispose() {
    //See? We're even disposing of things properly. What an elegant solution.
    super.dispose();
    GestureBinding.instance.pointerRouter.removeGlobalRoute(_handleEvent);
  }

  //We'll receive all the pointer events here:
  void _handleEvent(PointerEvent event) {
    //Make sure it is a stylus event:
    if(event.kind == PointerDeviceKind.stylus && _rb != null) {
      //Convert to the local coordinates:
      Offset coords = _rb.globalToLocal(event.position);

      //Make sure we are inside our component:
      if(coords.dx >= 0 && coords.dx < _rb.size.width && coords.dy >= 0 && coords.dy < _rb.size.height) {
        //Stylus is inside our component and we have its local coordinates. Yay!
        setState(() {
          _message = "dist=${event.distance} x=${coords.dx.toStringAsFixed(1)} y=${coords.dy.toStringAsFixed(1)}";
        });
      }
    }
  }

  @override
  void initState() {
    //Doing it this way, as suggested by this person: https://medium.com/@diegoveloper/flutter-widget-size-and-position-b0a9ffed9407
    WidgetsBinding.instance.addPostFrameCallback(_afterLayout);
    super.initState();
  }

  _afterLayout(_) {
    _rb = _containerKey.currentContext.findRenderObject();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                    //Event position will be converted to this container's local coordinate space:
                    key: _containerKey,
                    width: 200,
                    height: 200,
                    color: Colors.red
                ),
                Text(_message)
              ]
          )
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)