首页 > 编程技术 > android

flutter实现点击事件

发布时间:2020-8-26 13:57

本文实例为大家分享了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();
     }
    },
   ),
  ));
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持猪先飞。

标签:[!--infotagslink--]

您可能感兴趣的文章: