flutter中可以通过GestureDetector方法中的不同手势事件来实现不同的点击操作:
例如:
onTapDown 按下。
onTapUp 按下起来之后。
onTap 点击。
onTapCancel点击之后移出点击区域。
onDoubleTap双击。
onLongPress 长按。
以下代码演示了以上不同方法的操作:
class gustrueState extends StatefulWidget {
@override
State createState() {
return new StateFullGroupState();
}
}
class StateFullGroupState extends State {
//定义一个String类型的变量 用于打印说明
String printstring = '';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'nihao',
// theme: ThemeData(primaryColor: Colors.blue),
home: Scaffold(
appBar: AppBar(
title: Text('nihao'),
leading: GestureDetector(
onTap: () {
Text('点我返回');
},
child: Icon(Icons.arrow_back),
),
),
body: FractionallySizedBox(
//创建一个小部件,将其子部件的大小调整到总可用空间的一小部分
widthFactor: 1, //出入快递中给定的
child: Stack(
//一个小部件,其子部件的位置与其框的边缘关联
children: [
Column(
children: [
GestureDetector(
//手势侦查器 (有方法检测到不同的手势)
onTap: () => _printMsg('点击'),
onDoubleTap: () => _printMsg('双击'),
onLongPress: () => _printMsg('长按'),
onTapCancel: () => _printMsg('取消'),
onTapUp: (e) => _printMsg('松开'),
onTapDown: (e) => _printMsg('按下'),
child: Container( //被点击的对象child
padding: EdgeInsets.all(60),
decoration: BoxDecoration(color: Colors.blue),
child: Text(
'点我',
style: TextStyle(fontSize: 30, color: Colors.yellow),
),
),
),
//将点击的时间说明打印出来
Text(printstring),
],
)
],
),
),
));
}
/**
* 创建打印方法
*/
_printMsg(String s) {
setState(() {
printstring += ' ,$s';
});
}
}
eg:
flutter中制作一个跟随手势移动的控件
核心代码:
1 什么变量,用于指定手势的位置:
double Movex = 0;
double Movey = 0;
2 指定初始位置,确定图像的widget,实现onPanUpdate的事件
(onPanUpdate:一个与屏幕接触并移动之后的回调事件)
Positioned(
child: GestureDetector(
onPanUpdate: (e) => _doMove(e),
child: Container(
width: 50,
height: 50,
child: Text('nni'),
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(25)),
),
),
left: Movex,
top: Movey),
具体的doMove实现:
将movex和movey的值更改为回调之后的位置
_doMove(DragUpdateDetails e) {
setState(() {
Movex += e.delta.dx;
Movey += e.delta.dy;
});
}