SoFunction
Updated on 2025-03-11

flutter implements click event

The examples in this article share with you the specific code of flutter implementation click event for your reference. The specific content is as follows

In Android, you can bind OnClick to a button and other view by calling the method setOnClickListener.

In Flutter, there are two ways:

1. If Widget supports event listening, you can pass a function to it and process it. For example, RaisedButton has an onPressed parameter

@override
Widget build(BuildContext context) {
 return new RaisedButton(
  onPressed: () {
  print("click");
  },
  child: new Text("Button"));
}

2. If the Widget does not support event listening, you can wrap the Widget into the GestureDetector and pass the processing function to the onTap parameter

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. Using GestureDetector, you can listen to various gestures

(1)Tap

onTapDown
onTapUp
onTap
onTapCancel

(2)Double tap

onDoubleTap User taps the screen in the same position twice in a row

(3) Long press

onLongPress

(4) Drag vertically

onVerticalDragStart
onVerticalDragUpdate
onVerticalDragEnd

(5) Horizontal drag

onHorizontalDragStart
onHorizontalDragUpdate
onHorizontalDragEnd

2.2. Example: Listen to the double-click event of FlutterLogo, and rotate it when double-clicked.

void main() => runApp(DemoApp());

class DemoApp extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
 return new MaterialApp(
  title: 'Navigation Demo 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() {
 ();
 controller = new AnimationController(
  duration: const Duration(milliseconds: 2000), vsync: this);
 curve = new CurvedAnimation(parent: controller, curve: );
 }

 @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 () {
   ();
   } else {
   ();
   }
  },
  ),
 ));
 }
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.