flutter implements click events

  • 2021-12-05 07:18:42
  • OfStack

In this paper, we share the specific code of flutter to realize click events for your reference. The specific contents are as follows

In Android, you can bind OnClick to view such as buttons by calling the method setOnClickListener.

In Flutter, there are two methods:

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


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

2. If Widget does not support event listening, you can wrap the Widget into GestureDetector and pass the handler 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 for multiple gestures

(1) Tap

onTapDown
onTapUp
onTap
onTapCancel

(2)Double tap

The onDoubleTap user quickly taps the screen at 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: Listens for the FlutterLogo double-click event and causes it to rotate when double-clicked.


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

class DemoApp extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
 return new MaterialApp(
  title: ' Navigation demonstration 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();
   }
  },
  ),
 ));
 }
}

Related articles: