Last active
December 5, 2019 15:14
-
-
Save federicofazzeri/905d84f36ebd0ee4b9bab2552564bf44 to your computer and use it in GitHub Desktop.
Flutter simple circle canvas animation (DartPad link https://dartpad.dev/905d84f36ebd0ee4b9bab2552564bf44)
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 'dart:math'; | |
final Color darkBlue = Color.fromARGB(255, 18, 32, 47); | |
void main() { | |
runApp(MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue), | |
debugShowCheckedModeBanner: false, | |
home: Scaffold( | |
body: Center( | |
child: MyWidget(), | |
), | |
), | |
); | |
} | |
} | |
class MyWidget extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return Container( | |
width: 250, | |
height: 250, | |
padding: EdgeInsets.all(32.0), | |
child: Circle()); | |
} | |
} | |
class CirclePainter extends CustomPainter { | |
Paint _whiteArc = Paint() | |
..color = Colors.white | |
..style = PaintingStyle.stroke | |
..strokeCap = StrokeCap.round | |
..strokeWidth = 2.0; | |
double _completed = 0.0; | |
CirclePainter(this._completed); | |
@override | |
void paint(Canvas canvas, Size size) { | |
double centerX = size.width / 2.0; | |
double centerY = size.height / 2.0; | |
Offset centerOffset = Offset(centerX, centerY); | |
double radius = min(centerX, centerY); | |
double arcAngle = 2 * pi * (_completed / 100); | |
canvas.drawArc(Rect.fromCircle(center: centerOffset, radius: radius), | |
-pi / 2, arcAngle, false, _whiteArc); | |
} | |
@override | |
bool shouldRepaint(CirclePainter oldDelegate) { | |
return oldDelegate._completed != _completed; | |
} | |
} | |
class Circle extends StatefulWidget { | |
@override | |
State<StatefulWidget> createState() => _CircleState(); | |
} | |
class _CircleState extends State<Circle> with SingleTickerProviderStateMixin { | |
double _completed = 0; | |
Animation<double> _animation; | |
@override | |
void initState() { | |
super.initState(); | |
var controller = | |
AnimationController(duration: Duration(seconds: 10), vsync: this); | |
_animation = Tween(begin: 0.0, end: 100.0).animate(controller) | |
..addListener(() { | |
setState(() { | |
_completed = _animation.value; | |
}); | |
}); | |
controller.forward(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return CustomPaint(painter: CirclePainter(_completed)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment