使用flutter怎么实现一个点击事件

发布时间:2020-11-06 17:42:36 作者:Leah
来源:亿速云 阅读:502

使用flutter怎么实现一个点击事件?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

在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();
     }
    },
   ),
  ));
 }
}

看完上述内容,你们掌握使用flutter怎么实现一个点击事件的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

推荐阅读:
  1. 使用Flutter怎么实现一个文本组件
  2. 使用flutter怎么实现一个多布局列表

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

flutter 点击事件 lut

上一篇:在Android中利用viewpager实现一个画廊式效果

下一篇:一文读懂JS中的类型判断

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》