in Androidandroid
in Fluttermarkdown
下面两个例子对两种实现方法作简要说明:less
@override Widget build(BuildContext context) { return new RaisedButton( onPressed: () { print("click"); }, child: new Text("Button")); } 复制代码
这个例子描述了如何使用第一种方法实现点击事件监听。其实很简单,在构造RaisedButton时直接传递一个用于处理事件的方法给onPressed参数就能够了,当RaisedButton被点击时名为onPressed的参数所指向的方法就会被调用。在这里就是简单的打印出"click"。ide
Note: 这种方法仅当Widget自己已经支持事件监听时使用。好比这里的RaisedButton是系统提供的一个Widget,其自己已经支持了事件监听,因此能够直接在构造时传递一个用于处理事件的方法给它。oop
class SampleApp extends StatelessWidget { @override Widget build(BuildContext context) { return new Scaffold( body: new Center( child: new GestureDetector( child: new FlutterLogo( size: 200.0, ), onTap: () { print("tap"); }, ), )); } } 复制代码
这个例子描述了如何使用第二种方法实现点击事件监听。这里的关键是GestureDetector,咱们将须要响应点击事件的Widget包裹到GestureDetector内部,而且传递一个用来处理点击事件的方法给GestureDetector的onTap参数,当点击事件发生时onTap所指向的方法就会被调用。在这里就是简单的打印出"tap"。post
Note: 这种方法在Widget自己不支持事件监听时使用。动画
小结: 在Flutter中实现点击事件的监听处理有两种方法。 针对自己支持事件监听的Widget能够直接在构造Widget时传入一个方法用于点击事件处理。 针对自己不支持事件监听的Widget能够将其包裹在一个GestureDetector内部来实现点击事件处理。ui
in Androidthis
in Flutterspa
在Flutter中GestureDetector能够监听如下事件:
Tap
Double tap
Long press
Vertical drag
Horizontal drag
下面的例子简单展现了如何使用GestureDetector来监听一个Double tap事件:
AnimationController controller; CurvedAnimation curve; @override void initState() { controller = new AnimationController(duration: const Duration(milliseconds: 2000), vsync: this); curve = new CurvedAnimation(parent: controller, curve: Curves.easeIn); } class SampleApp extends StatelessWidget { @override Widget build(BuildContext context) { return new Scaffold( body: new Center( child: new GestureDetector( child: new RotationTransition( turns: curve, child: new FlutterLogo( size: 200.0, )), onDoubleTap: () { if (controller.isCompleted) { controller.reverse(); } else { controller.forward(); } }, ), )); } } 复制代码
在这个例子中咱们想让一个FlutterLogo响应Double tap事件,可是FlutterLogo自己是不支持事件处理的Widget,因此这里将其包裹在GestureDetector内部,并经过GestureDetector的onDoubleTap参数来传递一个用于处理Double tap事件的方法。 由于这个例子是想FlutterLogo在接收到Double tap事件后去执行一个旋转动画,因此这里并非直接将FlutterLogo包裹在GestureDetector内部,而是先用描述一个旋转动画的组件RotationTransition包裹FlutterLogo,接着再在外层用GestureDetector包裹RotationTransition组件。关于在Flutter中实现动画的介绍能够参阅FFAD-Views。
小结: 在Flutter中使用GestureDetector能够监听处理大多数类型的事件,使用时只要将咱们想要接收事件的Widget包裹在GestureDetector内部,并传递事件处理方法给相应的参数便可。