Flutter开发之——事件监听
在Flutter中,事件监听通常是通过Widgets的事件回调来实现的。以下是一些常见的事件监听示例:
- 点击事件监听(GestureDetector Widget):
GestureDetector(
onTap: () {
print('Container was tapped!');
},
child: Container(
color: Colors.blue,
child: Text('Tap Me'),
),
)
- 长按事件监听:
GestureDetector(
onLongPress: () {
print('Container was long-pressed!');
},
child: Container(
color: Colors.blue,
child: Text('Long Press Me'),
),
)
- 拖拽事件监听:
GestureDetector(
onPanUpdate: (DragUpdateDetails details) {
print('Container was dragged!');
},
child: Container(
color: Colors.blue,
child: Text('Drag Me'),
),
)
- Stream监听(例如,文本框输入变化):
StreamBuilder<String>(
stream: myBloc.inputStream,
builder: (context, snapshot) {
return TextField(
onChanged: (value) {
myBloc.updateInput(value);
},
decoration: InputDecoration(hintText: 'Type something'),
);
},
)
- 按钮点击事件监听:
RaisedButton(
onPressed: () {
print('Button was pressed!');
},
child: Text('Press Me'),
)
这些是在Flutter中实现事件监听的常见方法。每个Widget都有自己的事件回调,例如onTap
、onLongPress
、onChanged
和onPressed
等。使用这些回调,你可以在事件发生时执行相关的代码。
评论已关闭