一、指针事件Pointer
Pointer 代表的是人机界面交互的原始数据。一共有四种指针事件:
PointerDownEvent 指针在特定位置与屏幕接触PointerMoveEvent 指针从屏幕的一个位置移动到另外一个位置PointerUpEvent 指针与屏幕停止接触PointerCancelEvent 指针因为一些特殊情况被取消
Pointer的原理是什么呢?
在指针落下时,框架做了一个 hit test 的操作,确定与屏幕发生接触的位置上有哪些Widget以及分发给最内部的组件去响应;
事件会沿着最内部的组件向组件树的根冒泡分发;
并且不存在用于取消或者停止指针事件进一步分发的机制;
二、手势识别GestureDetector
GestureDetector({
Key? key,
this.child,
this.onTapDown,
this.onTapUp,
this.onTap,
this.onTapCancel,
this.onSecondaryTap,
this.onSecondaryTapDown,
this.onSecondaryTapUp,
this.onSecondaryTapCancel,
this.onTertiaryTapDown,
this.onTertiaryTapUp,
this.onTertiaryTapCancel,
this.onDoubleTapDown,
this.onDoubleTap,
this.onDoubleTapCancel,
this.onLongPressDown,
this.onLongPressCancel,
this.onLongPress,
this.onLongPressStart,
this.onLongPressMoveUpdate,
this.onLongPressUp,
this.onLongPressEnd,
this.onSecondaryLongPressDown,
this.onSecondaryLongPressCancel,
this.onSecondaryLongPress,
this.onSecondaryLongPressStart,
this.onSecondaryLongPressMoveUpdate,
this.onSecondaryLongPressUp,
this.onSecondaryLongPressEnd,
this.onTertiaryLongPressDown,
this.onTertiaryLongPressCancel,
this.onTertiaryLongPress,
this.onTertiaryLongPressStart,
this.onTertiaryLongPressMoveUpdate,
this.onTertiaryLongPressUp,
this.onTertiaryLongPressEnd,
this.onVerticalDragDown,
this.onVerticalDragStart,
this.onVerticalDragUpdate,
this.onVerticalDragEnd,
this.onVerticalDragCancel,
this.onHorizontalDragDown,
this.onHorizontalDragStart,
this.onHorizontalDragUpdate,
this.onHorizontalDragEnd,
this.onHorizontalDragCancel,
this.onForcePressStart,
this.onForcePressPeak,
this.onForcePressUpdate,
this.onForcePressEnd,
this.onPanDown,
this.onPanStart,
this.onPanUpdate,
this.onPanEnd,
this.onPanCancel,
this.onScaleStart,
this.onScaleUpdate,
this.onScaleEnd,
this.behavior,
this.excludeFromSemantics = false,
this.dragStartBehavior = DragStartBehavior.start,
})
三、跨组件事件EventBus
在组件之间如果有事件需要传递,一方面可以一层层来传递,另一方面我们也可以使用一个EventBus工具来完成。
其实EventBus是一种非常常见的跨组件通信的方式:
EventBus相当于是一种订阅者模式,通过一个全局的对象来管理;这个EventBus我们可以自己实现,也可以使用第三方的EventBus;
这里我们直接选择第三方的EventBus:
dependencies:
event_bus: ^1.1.1
第一:我们需要定义一个希望在组件之间传递的对象:
我们可以称之为一个时间对象,也可以是我们平时开发中用的模型对象(model)
class UserInfo {
String nickname;
int level;
UserInfo(this.nickname, this.level);
}
第二:创建一个全局的EventBus对象
final eventBus = EventBus();
第三:在某个Widget中,发出事件:
class HYButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return RaisedButton(
child: Text(“HYButton”),
onPressed: () {
final info = UserInfo(“why”, 18);
eventBus.fire(info);
},
);
}
}
第四:在某个Widget中,监听事件
class HYText extends StatefulWidget {
@override
_HYTextState createState() => _HYTextState();
}
class _HYTextState extends State
String message = “Hello Coderwhy”;
@override
void initState() {
super.initState();
eventBus.on<UserInfo>().listen((data) {<br /> setState(() {<br /> message = "${data.nickname}-${data.level}";<br /> });<br /> });<br /> }
@override
Widget build(BuildContext context) {
return Text(message, style: TextStyle(fontSize: 30),);
}
}