Last active
May 6, 2024 10:09
-
-
Save sgruhier/017ae34ff40b1d5e924b440b53c457f8 to your computer and use it in GitHub Desktop.
Flutter physics animation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'package:flutter/physics.dart'; | |
class DraggableSquare extends StatefulWidget { | |
const DraggableSquare({super.key}); | |
@override | |
State<DraggableSquare> createState() => _DraggableSquareState(); | |
} | |
class _DraggableSquareState extends State<DraggableSquare> with SingleTickerProviderStateMixin { | |
var originalPostion = const Offset(150.0, 150.0); | |
late double _left; | |
late double _top; | |
late AnimationController _controller; | |
late Animation<Offset> _animation; | |
@override | |
void initState() { | |
super.initState(); | |
_left = originalPostion.dx; | |
_top = originalPostion.dy; | |
_controller = AnimationController.unbounded(vsync: this) | |
..addListener(() { | |
setState(() { | |
_left = _animation.value.dx; | |
_top = _animation.value.dy; | |
}); | |
}); | |
} | |
@override | |
void dispose() { | |
_controller.dispose(); | |
super.dispose(); | |
} | |
void _runAnimation() { | |
_animation = _controller.drive(Tween<Offset>( | |
begin: Offset(_left, _top), | |
end: originalPostion, | |
)); | |
const spring = SpringDescription( | |
mass: 1.0, | |
stiffness: 100.0, | |
damping: 10.0, | |
); | |
final simulation = SpringSimulation(spring, 0.0, 1.0, 0); | |
_controller.animateWith(simulation); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return GestureDetector( | |
onPanDown: (details) { | |
_controller.stop(); | |
}, | |
onPanUpdate: (details) { | |
setState(() { | |
_left += details.delta.dx; | |
_top += details.delta.dy; | |
}); | |
}, | |
onPanEnd: (details) { | |
_runAnimation(); | |
}, | |
child: Stack( | |
children: [ | |
Positioned( | |
left: _left, | |
top: _top, | |
child: Container( | |
width: 100.0, | |
height: 100.0, | |
color: Colors.blue, | |
), | |
), | |
], | |
), | |
); | |
} | |
} | |
void main() { | |
runApp(const MaterialApp( | |
home: Scaffold( | |
body: DraggableSquare(), | |
), | |
)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment