class _GestureTestState extends State<GestureTest> {
String _operation = "No detected!"; //事件名稱
@override
Widget build(BuildContext context) {
return Center(
child: GestureDetector(
child: Container(
alignment: Alignment.center,
color: Colors.red,
width: 200.0,
height: 100.0,
child: Text(
_operation,
style: TextStyle(color: Colors.white),
),
),
onTap: () => updateText("Tap"), //點擊
onDoubleTap: () => updateText("DoubleTap"), //雙點擊
onLongPress: () => updateText("LongPress"), //長按
),
);
}
void updateText(String text) {
//更新事件名稱
setState(() {
_operation = text;
});
}
}
class _Drag extends StatefulWidget {
@override
_DragState createState() => _DragState();
}
class _DragState extends State<_Drag> with SingleTickerProviderStateMixin {
double _top = 0.0;
double _left = 0.0;
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
Positioned(
top: _top,
left: _left,
child: GestureDetector(
child: CircleAvatar(child: Text("A")),
//手指按下時會觸發此回調
onPanDown: (DragDownDetails e) {
//印出按下的位置(相對於螢幕)
print("使用者手指按下:${e.globalPosition}");
},
//手指滑動時會觸發此回調
onPanUpdate: (DragUpdateDetails e) {
setState(() {
_left += e.delta.dx;
_top += e.delta.dy;
});
},
//手指離開時會觸發此回調
onPanEnd: (DragEndDetails e){
//列印滑動結束時的速度
print(e.velocity);
},
),
)
],
);
}
}
DragDownDetails.globalPosition為按下的位置,是相對於螢幕原點的偏移;DragUpdateDetails.delta為滑動時,會觸發多次Update,而Update可以取得滑動的偏移量;DragEndDetails.velocity為抬起手指時的滑動速度(包含x、y兩個軸的),範例中並沒有處理手指抬起時的速度,常見的效果是根據使用者抬起手指時的速度做一個減速動畫。
class _Scale extends StatefulWidget {
const _Scale({Key? key}) : super(key: key);
@override
_ScaleState createState() => _ScaleState();
}
class _ScaleState extends State<_Scale> {
double _width = 100.0;
@override
Widget build(BuildContext context) {
return Center(
child: GestureDetector(
//指定寬度,高度自適應
child: Image.asset("your_image_path", width: _width),
onScaleUpdate: (ScaleUpdateDetails details) {
setState(() {
//縮放倍數在0.8到10倍之間
_width=100*details.scale.clamp(.8, 10.0);
});
},
),
);
}
}
class _GestureRecognizer extends StatefulWidget {
const _GestureRecognizer({Key? key}) : super(key: key);
@override
_GestureRecognizerState createState() => _GestureRecognizerState();
}
class _GestureRecognizerState extends State<_GestureRecognizer> {
TapGestureRecognizer _tapGestureRecognizer = TapGestureRecognizer();
bool _toggle = false;
@override
void dispose() {
//釋放資源
_tapGestureRecognizer.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Center(
child: Text.rich(
TextSpan(
children: [
TextSpan(text: "Button"),
TextSpan(
text: "Change",
style: TextStyle(
fontSize: 30.0,
color: _toggle ? Colors.blue : Colors.red,
),
recognizer: _tapGestureRecognizer
..onTap = () {
setState(() {
_toggle = !_toggle;
});
},
),
TextSpan(text: "Button"),
],
),
),
);
}
}