引言:
GestureDetector在Flutter中負(fù)責(zé)處理跟用戶的簡(jiǎn)單手勢(shì)交互亚皂,GestureDetector控件沒有圖像展示俱箱,只是檢測(cè)用戶輸入的手勢(shì),并作出相應(yīng)的處理孕讳,包括點(diǎn)擊匠楚、拖動(dòng)和縮放。許多控件使用GestureDetector為其他控件提供回調(diào)厂财,比如IconButton芋簿、RaisedButton和FloatingActionButton控件有onPressed回調(diào),當(dāng)用戶點(diǎn)擊控件時(shí)觸發(fā)回調(diào)璃饱,當(dāng)用戶點(diǎn)擊控件時(shí)觸發(fā)回調(diào)与斤。
我們來一起看下GestureDetector的構(gòu)造方法:
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
})
從構(gòu)造方法中,我們看出GestureDetector構(gòu)造方法里定義各種事件回調(diào),還有一個(gè)child屬性撩穿,這就意味著我們可以利用GestureDetector包裹本身不支持點(diǎn)擊回調(diào)事件的Widget賦予它們點(diǎn)擊回調(diào)能力磷支,像Text、Image我們就不能像使用RaisedButton一樣直接給Text食寡、Image綁定onPress回調(diào)雾狈,但是我們可以借助GestureDetector完成這一操作。
如圖我給Text賦予了各種事件交互:
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("我被賦予了點(diǎn)擊觸摸能力...",style: new TextStyle(fontSize: 20.0),),
onTap: () {
print("------onTap");
},
onDoubleTap: () {
print("------onDoubleTap");
},
onLongPress: () {
print("-----onLongPress");
},
onVerticalDragStart: (details){
print("在垂直方向開始位置:"+details.globalPosition.toString());
}, onVerticalDragEnd: (details){
print("在垂直方向結(jié)束位置:"+details.primaryVelocity.toString());
},
)),
);
}
}
我們?cè)趌og命令行抓取到的各種回調(diào)事件的交互: