flutter如何实现点击事件
【摘要】 在Android中,您可以通过调用方法setOnClickListener将OnClick绑定到按钮等view上。 在Flutter中,有两种方法:
1.如果Widget支持事件监听,则可以将一个函数传递给它并进行处理。例如,RaisedButton有一个onPressed参数
@override
Widget build(BuildContext context)...
在Android中,您可以通过调用方法setOnClickListener将OnClick绑定到按钮等view上。
在Flutter中,有两种方法:
1.如果Widget支持事件监听,则可以将一个函数传递给它并进行处理。例如,RaisedButton有一个onPressed参数
@override
Widget build(BuildContext context) {
return new RaisedButton( onPressed: () { print("click"); }, child: new Text("Button"));
}
2.如果Widget不支持事件监听,则可以将该Widget包装到GestureDetector中,并将处理函数传递给onTap参数
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"); }, ), ));
}
}
2.1.使用GestureDetector,可以监听多种手势
(1)Tap
- onTapDown
- onTapUp
- onTap
- onTapCancel
(2)Double tap
- onDoubleTap 用户快速连续两次在同一位置轻敲屏幕
(3)长按
- onLongPress
(4)垂直拖动
- onVerticalDragStart
- onVerticalDragUpdate
- onVerticalDragEnd
(5)水平拖拽
- onHorizontalDragStart
- onHorizontalDragUpdate
- onHorizontalDragEnd
2.2.示例:监听FlutterLogo的双击事件,双击时使其旋转。
void main() => runApp(DemoApp());
class DemoApp extends StatelessWidget {
@override
Widget build(BuildContext context) { return new MaterialApp( title: '导航演示1', home: new MyAppHome(), );
}
}
class MyAppHome extends StatefulWidget{
@override
_MyAppHomeState createState() => _MyAppHomeState();
}
class _MyAppHomeState extends State<MyAppHome> with TickerProviderStateMixin{
AnimationController controller;
CurvedAnimation curve; @override
void initState() { super.initState(); controller = new AnimationController( duration: const Duration(milliseconds: 2000), vsync: this); curve = new CurvedAnimation(parent: controller, curve: Curves.easeIn);
} @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(); } }, ), ));
}
}
文章来源: blog.csdn.net,作者:WongKyunban,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/weixin_40763897/article/details/108201619
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)