事件监听
指针事件Pointer
Listener
onPointerDown
onPointerMove
onPointerUp
onPointerHover
onPointerCancel
onPointerSignal
child: Listener(
onPointerDown: (event) {
print("down ${event.position}");
},
onPointerMove: (event) {
print("move ${event.localPosition}");
},
child: Container(
width: 200,
height: 200,
color: Colors.red,
),
),
手势识别Gesture
GestureDetector
onTapDown
onTapCancel
onDoubleTapDown
onLongPressDown
- ......
child: GestureDetector(
onTapDown: (details) {
print("onTapDown");
},
child: Container(
width: 200,
height: 200,
color: Colors.red,
),
)
child: GestureDetector(
onTapDown: (details) {
print("outer click");
},
child: Container(
width: 200,
height: 200,
color: Colors.red,
alignment: Alignment.center,
child: GestureDetector(
onTapDown: (details) {
print("inner click");
},
child: Container(
width: 100,
height: 100,
color: Colors.purple,
),
),
),
)
问题:当点击子模块 purple
的时候,父模块 red
偶尔也会响应手势方法。
解决方法为使用 Stack
取消父子层级关系。
child: Stack(
alignment: Alignment.center,
children: [
GestureDetector(
onTapDown: (details) {
print("outer click");
},
child: Container(
width: 200,
height: 200,
color: Colors.red,
),
),
GestureDetector(
onTapDown: (details) {
print("inner click");
},
child: Container(
width: 100,
height: 100,
color: Colors.purple,
),
),
],
)
IgnorePointer
可忽略手势
IgnorePointer(
child: GestureDetector(
onTapDown: (details) {
print("inner click");
},
child: Container(
width: 100,
height: 100,
color: Colors.purple,
),
),
),
跨组件事件
导入库 event_bus
创建一个全局的 EventBus
对象
final eventBus = EventBus();
eventBus.fire
发出事件
class GoButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return FloatingActionButton(onPressed: () {
eventBus.fire(UserInfo("name", 20));
});
}
}
eventBus.on
监听事件
class GoText extends StatefulWidget {
@override
State<GoText> createState() => _GoTextState();
}
class _GoTextState extends State<GoText> {
String _message = "message";
@override
void initState() {
super.initState();
eventBus.on<UserInfo>().listen((event) {
setState(() {
_message = "name=${event.name}, age=${event.age}";
});
});
}
@override
Widget build(BuildContext context) {
return Text(_message);
}
}