Created
August 12, 2020 09:01
-
-
Save mayurdhurpate/803c09dcc9d046db50f47979a9301d6e to your computer and use it in GitHub Desktop.
A basic example of CustomPainter with animating Circle.
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:math'; | |
import 'package:flutter/material.dart'; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Circle Builder', | |
debugShowCheckedModeBanner: false, | |
home: CircleBackground(), | |
); | |
} | |
} | |
class CircleBackground extends StatefulWidget { | |
@override | |
_CircleBackgroundState createState() => _CircleBackgroundState(); | |
} | |
class _CircleBackgroundState extends State<CircleBackground> { | |
@override | |
Widget build(BuildContext context) { | |
return SafeArea( | |
child: Scaffold( | |
backgroundColor: Colors.white, | |
body: Circle(), | |
), | |
); | |
} | |
} | |
class Circle extends StatefulWidget { | |
@override | |
_CircleState createState() => _CircleState(); | |
} | |
class _CircleState extends State<Circle> with SingleTickerProviderStateMixin { | |
double _fraction = 0.0; | |
Animation<double> _animation; | |
AnimationController _controller; | |
@override | |
void initState() { | |
super.initState(); | |
_controller = AnimationController( | |
duration: Duration(milliseconds: 2500), | |
vsync: this, | |
); | |
_animation = Tween(begin: 0.0, end: 1.0).animate(_controller) | |
..addListener(() { | |
setState(() { | |
_fraction = _animation.value; | |
}); | |
}); | |
_controller.forward(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Container( | |
child: Center( | |
child: AspectRatio( | |
aspectRatio: 1.0, | |
child: Padding( | |
padding: const EdgeInsets.all(24.0), | |
child: CustomPaint( | |
painter: CirclePainter(fraction: _fraction), | |
), | |
), | |
), | |
), | |
); | |
} | |
@override | |
void dispose() { | |
_controller.dispose(); | |
super.dispose(); | |
} | |
} | |
class CirclePainter extends CustomPainter { | |
final double fraction; | |
var _circlePaint; | |
CirclePainter({this.fraction}) { | |
_circlePaint = Paint() | |
..color = Colors.black | |
..style = PaintingStyle.stroke | |
..strokeWidth = 12.0 | |
..strokeCap = StrokeCap.round; | |
} | |
@override | |
void paint(Canvas canvas, Size size) { | |
var rect = Offset(0.0, 0.0) & size; | |
canvas.drawArc(rect, -pi / 2, pi * 2 * fraction, false, _circlePaint); | |
} | |
@override | |
bool shouldRepaint(CirclePainter oldDelegate) { | |
return oldDelegate.fraction != fraction; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment