1. 程式人生 > 程式設計 >flutter實現點選事件

flutter實現點選事件

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。