原始指针事件

人间烟火/张佳伟版 Lv2
原始指针事件:Pointer Event

Flutter中可以采用Listener来监听原始触摸事件:

1
2
3
4
5
6
7
8
9
Listener({
Key key,
this.onPointerDown, //手指按下回调
this.onPointerMove, //手指移动回调
this.onPointerUp,//手指抬起回调
this.onPointerCancel,//触摸事件取消回调
this.behavior = HitTestBehavior.deferToChild, //先忽略此参数,后面小节会专门介绍
Widget child
})

下面代码功能是: 手指在一个容器上移动时查看手指相对于容器的位置
(Listener包含住的空间才触发监听)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class _PointerMoveIndicatorState extends State<PointerMoveIndicator> {
PointerEvent? _event;

@override
Widget build(BuildContext context) {
return Listener(
child: Container(
alignment: Alignment.center,
color: Colors.blue,
width: 300.0,
height: 150.0,
child: Text(
'${_event?.localPosition ?? ''}',
style: TextStyle(color: Colors.white),
),
),
onPointerDown: (PointerDownEvent event) => setState(() => _event = event),
onPointerMove: (PointerMoveEvent event) => setState(() => _event = event),
onPointerUp: (PointerUpEvent event) => setState(() => _event = event),
);
}
}
2、对于上述监听事件,存在忽略指针事件

不想让某个子树响应PointerEvent的话,我们可以使用IgnorePointer和AbsorbPointer,这两个组件都能阻止子树接收指针事件,不同之处在于AbsorbPointer本身会参与命中测试,而IgnorePointer本身不会参与,这就意味着AbsorbPointer本身是可以接收指针事件的(但其子树不行),而IgnorePointer不可以

1
2
3
4
5
6
7
8
9
10
11
12
13
Listener(
child: AbsorbPointer(
child: Listener(
child: Container(
color: Colors.red,
width: 200.0,
height: 100.0,
),
onPointerDown: (event)=>print("in"),
),
),
onPointerDown: (event)=>print("up"),
)

点击Container时,由于它在AbsorbPointer的子树上,所以不会响应指针事件,所以日志不会输出”in”,但AbsorbPointer本身是可以接收指针事件的,所以会输出”up”。如果将AbsorbPointer换成IgnorePointer,那么两个都不会输出

  • Title: 原始指针事件
  • Author: 人间烟火/张佳伟版
  • Created at: 2024-05-15 13:15:56
  • Updated at: 2024-05-22 22:39:06
  • Link: https://945912035.github.io/2024/05/15/2024-05-15/
  • License: This work is licensed under CC BY-NC-SA 4.0.
 Comments
On this page
原始指针事件