Created
March 23, 2025 15:14
-
-
Save chooyan-eng/7c4a910b5862909870a5d1148cfca3e5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 'dart:async'; | |
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 _controllerX; | |
late final AnimationController _controllerY; | |
double _valueX = 20; | |
double _valueY = 20; | |
@override | |
void initState() { | |
super.initState(); | |
_controllerX = AnimationController.unbounded( | |
vsync: this, | |
duration: Duration(seconds: 1), | |
)..addListener(() { | |
setState(() => _valueX = _controllerX.value); | |
}); | |
_controllerY = AnimationController.unbounded( | |
vsync: this, | |
duration: Duration(seconds: 1), | |
)..addListener(() { | |
setState(() => _valueY = _controllerY.value); | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
body: Stack( | |
children: [ | |
CustomPaint(size: Size.infinite, painter: _GridPainter()), | |
Positioned( | |
left: _valueX, | |
top: _valueY, | |
child: Container(width: 60, height: 60, color: Colors.blue), | |
), | |
], | |
), | |
floatingActionButton: FloatingActionButton( | |
onPressed: () { | |
_controllerY.animateWith(GravitySimulation(2000, 20, 1000, 0)); | |
Timer(Duration(milliseconds: 500), () { | |
final velocity = _controllerY.velocity; | |
final description = SpringDescription( | |
mass: 0.8, | |
stiffness: 50, | |
damping: 10, | |
); | |
_controllerY.stop(); | |
_controllerX.animateWith( | |
SpringSimulation(description, _valueX, 200, velocity), | |
); | |
_controllerY.animateWith( | |
SpringSimulation(description, _valueY, 100, velocity), | |
); | |
}); | |
}, | |
), | |
); | |
} | |
} | |
/// 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