Skip to content

Instantly share code, notes, and snippets.

@Barttje
Last active August 13, 2020 13:00
Show Gist options
  • Save Barttje/0266e87e1c1e064d76d8a0575344ff46 to your computer and use it in GitHub Desktop.
Save Barttje/0266e87e1c1e064d76d8a0575344ff46 to your computer and use it in GitHub Desktop.
Circle animation
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: CircleAnimation(),
);
}
}
class CircleAnimation extends StatefulWidget {
@override
_CircleAnimationState createState() => _CircleAnimationState();
}
class _CircleAnimationState extends State<CircleAnimation>
with SingleTickerProviderStateMixin {
Animation<double> animation;
AnimationController controller;
bool isLeft = true;
bool runOnce = false;
@override
void initState() {
super.initState();
controller =
AnimationController(duration: const Duration(seconds: 2), vsync: this);
animation = Tween<double>(begin: 0, end: 100).animate(controller)
..addListener(() {
setState(() {});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: RaisedButton(
child: Text("Press me"),
onPressed: (() {
if (!controller.isAnimating) {
if (runOnce) {
isLeft = !isLeft;
} else {
runOnce = true;
}
controller.reset();
controller.forward();
}
}),
)),
body: CustomPaint(
painter:
CirclePainter(isLeft ? animation.value : 100 - animation.value),
child: Container(
width: double.infinity,
),
),
);
}
}
class CirclePainter extends CustomPainter {
double x;
CirclePainter(this.x);
@override
void paint(Canvas canvas, Size size) {
Offset center = Offset(size.width * x / 100, 20);
canvas.drawCircle(center, 30, Paint()..color = Colors.green);
}
@override
bool shouldRepaint(CirclePainter oldDelegate) => this.x != oldDelegate.x;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment