Flutter – Physics Simulation in Animation
Physics simulation in Flutter is a beautiful way to Animate components of the flutter app to make it look more realistic and interactive. These can be used to create a range of animations like falling objects due to gravity to making a container seem attached to a spring. In this article, we will explore the same by building a simple application.
Follow the below steps to create a simple physics simulation in a Widget:
- Develop an Animation controller.
- Use gestures for movement.
- Display the animation.
- Use velocity to simulate the springing motion.
Let’s discuss them in detail:
Developing an Animation Controller:
To create the Animation controller make a StatefulWidget called DraggableCard as shown below:
Using gestures for movement:
Here we will make the widget move when dragged in any direction. The movement can be mapped using a GestureDetector that handles onPanEnd, onPanUpdate, and onPanDown as shown below:
Use the Animation<Alignment> field and the _runAnimation method to produce a spring like spring-like effect as shown below to display the Animation:
Now, whenever the Animation Controller produces a value update the _dragAlignment field as shown below:
Now, use the _dragAlignment field to Align the widget as shown below:
Finally manage the Animation using the GestureDetector as follows:
Using velocity to simulate the springing motion:
First, import the Physics package as below:
Now use the animateWith() method of the AnimationController to create a spring-like effect as shown below:
Finally, make a call to _runAnimation() method with velocity and size as a parameter as shown below:
Complete Source Code:
Please Login to comment...