GestureDetector
onTap、onDoubleTap和onLongPress
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;
});
}
}
onPanDown、onPanUpdate和onPanEnd
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兩個軸的),範例中並沒有處理手指抬起時的速度,常見的效果是根據使用者抬起手指時的速度做一個減速動畫。Scale
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(() {
_width=100*details.scale.clamp(.8, 10.0);
});
},
),
);
}
}
GestureRecognizer
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"),
],
),
),
);
}
}