例如,我有一个小部件,可在用户滑动时使用变量dragoffset += details.offset.dx
旋转它;
滑动结束后如何向旋转增加惯量?例如。当您松开手指时,对象将继续以下降的速度旋转-就像ListView的正常行为一样。
这里有一些样板代码示例:
Widget rotatedWidget() {
double fingerOffset = 0.0;
return GestureDetector(
onHorizontalDragUpdate: (details) {
setState((){
fingerOffset += details.delta.dx;
});
},
onHorizontalDragEnd: (details) {
/// some code to add inertia
},
child: Transform.rotate(
angle: offset,
child: Container(width: 100, height: 100, color: Colors.blue),
));
}
感谢@pskink此解决方案。
AnimationController ctrl;
@override
void initState() {
super.initState();
ctrl = AnimationController.unbounded(vsync: this);
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onPanUpdate: (d) => ctrl.value += d.delta.dx / 100,
onPanEnd: (d) {
ctrl.animateWith(
FrictionSimulation(
0.05, // <- the bigger this value, the less friction is applied
ctrl.value,
d.velocity.pixelsPerSecond.dx / 100 // <- Velocity of inertia
));
},
child: Scaffold(
appBar: AppBar(
title: Text('RotatedBox'),
),
body: AnimatedBuilder(
animation: ctrl,
builder: (ctx, w) {
return Center(
child: Transform.rotate(
angle: ctrl.value,
child: Container(width: 100, height: 100, color: Colors.blue),
),
);
},
),
),
);
}