Skip to content

Instantly share code, notes, and snippets.

@chooyan-eng
Created March 23, 2025 15:25
Show Gist options
  • Save chooyan-eng/7746a8b6bca0b6da122cd60e4943df3e to your computer and use it in GitHub Desktop.
Save chooyan-eng/7746a8b6bca0b6da122cd60e4943df3e to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
import 'package:flutter/physics.dart';
void main() {
runApp(const MaterialApp(home: AnimationPage()));
}
class AnimationPage extends StatefulWidget {
const AnimationPage({super.key});
@override
State<AnimationPage> createState() => _AnimationPageState();
}
class _AnimationPageState extends State<AnimationPage>
with TickerProviderStateMixin {
late final AnimationController _controller;
final _boxSize = 60.0;
double _value = 20;
@override
void initState() {
super.initState();
_controller = AnimationController.unbounded(
vsync: this,
duration: Duration(seconds: 1),
)..addListener(() {
setState(() => _value = _controller.value);
// y of the ground
final ground = MediaQuery.of(context).size.height - 100 - _boxSize;
if (_value > ground) {
// box now touches the ground
// retrieve the velocity of slightly weaker to opposite(upper) direction
final velocity = _controller.velocity * -1 * 0.7;
// stop previous animation
_controller.stop();
// start new animation
_controller.animateWith(
GravitySimulation(2000, ground - 1, 1000, velocity),
);
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
CustomPaint(size: Size.infinite, painter: _GridPainter()),
Positioned(
left: 20,
top: _value,
child: Container(width: 60, height: 60, color: Colors.blue),
),
Positioned(
left: 0,
right: 0,
bottom: 0,
child: Container(height: 100, color: Colors.brown),
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
_controller.animateWith(GravitySimulation(2000, 20, 1000, 0));
},
),
);
}
}
/// background grid
class _GridPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final paint =
Paint()
..color = Colors.grey.withOpacity(0.3)
..strokeWidth = 0.5;
for (var i = 0.0; i < size.width; i += 10) {
canvas.drawLine(Offset(i, 0), Offset(i, size.height), paint);
}
for (var i = 0.0; i < size.height; i += 10) {
canvas.drawLine(Offset(0, i), Offset(size.width, i), paint);
}
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment