Flutter入門進階之旅(七)GestureDetector

引言:

GestureDetector在Flutter中負責處理跟用戶的簡單手勢交互,GestureDetector控件沒有圖像展現,只是檢測用戶輸入的手勢,並做出相應的處理,包括點擊、拖動和縮放。許多控件使用GestureDetector爲其餘控件提供回調,好比IconButton、RaisedButton和FloatingActionButton控件有onPressed回調,當用戶點擊控件時觸發回調,當用戶點擊控件時觸發回調。java

咱們來一塊兒看下GestureDetector的構造方法:app

GestureDetector({
    Key key,
    this.child,
    this.onTapDown,
    this.onTapUp,
    this.onTap,
    this.onTapCancel,
    this.onDoubleTap,
    this.onLongPress,
    this.onLongPressUp,
    this.onVerticalDragDown,
    this.onVerticalDragStart,
    this.onVerticalDragUpdate,
    this.onVerticalDragEnd,
    this.onVerticalDragCancel,
    this.onHorizontalDragDown,
    this.onHorizontalDragStart,
    this.onHorizontalDragUpdate,
    this.onHorizontalDragEnd,
    this.onHorizontalDragCancel,
    this.onForcePressStart,
    this.onForcePressPeak,
    this.onForcePressUpdate,
    this.onForcePressEnd,
    this.onPanDown,
    this.onPanStart,
    this.onPanUpdate,
    this.onPanEnd,
    this.onPanCancel,
    this.onScaleStart,
    this.onScaleUpdate,
    this.onScaleEnd,
    this.behavior,
    this.excludeFromSemantics = false
  }) 


複製代碼

從構造方法中,咱們看出GestureDetector構造方法裏定義各類事件回調,還有一個child屬性,這就意味着咱們能夠利用GestureDetector包裹自己不支持點擊回調事件的Widget賦予它們點擊回調能力,像Text、Image咱們就不能像使用RaisedButton同樣直接給Text、Image綁定onPress回調,可是咱們能夠藉助GestureDetector完成這一操做。less

如圖我給Text賦予了各類事件交互: ide

在這裏插入圖片描述

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(home: new MyApp()));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Gestures"),
      ),
      body: new Center(
          child: new GestureDetector(
            child: new Text("我被賦予了點擊觸摸能力...",style: new TextStyle(fontSize: 20.0),),
            onTap: () {
              print("------onTap");
            },
            onDoubleTap: () {
              print("------onDoubleTap");
            },
            onLongPress: () {
              print("-----onLongPress");
            },
            onVerticalDragStart: (details){
              print("在垂直方向開始位置:"+details.globalPosition.toString());
            }, onVerticalDragEnd: (details){
            print("在垂直方向結束位置:"+details.primaryVelocity.toString());
          },
          )),
    );
  }
}
複製代碼

咱們在log命令行抓取到的各類回調事件的交互: ui

在這裏插入圖片描述
相關文章
相關標籤/搜索