Last active
August 10, 2021 22:05
-
-
Save funwithflutter/c1838c8ac832a9e4935ccd7f516b9fe0 to your computer and use it in GitHub Desktop.
Paint demo with a simple animation. Creates a loading bar.
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 'dart:math'; | |
import 'package:flutter/material.dart'; | |
void main() => runApp(const MyApp()); | |
class MyApp extends StatelessWidget { | |
const MyApp({Key? key}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
showPerformanceOverlay: false, | |
title: 'Paint Demo', | |
home: Scaffold( | |
appBar: AppBar( | |
title: const Text('Paint Demo'), | |
), | |
body: const Center( | |
child: PaintDemo(), | |
), | |
), | |
); | |
} | |
} | |
class PaintDemo extends StatefulWidget { | |
const PaintDemo({Key? key}) : super(key: key); | |
@override | |
_PaintDemoState createState() => _PaintDemoState(); | |
} | |
class _PaintDemoState extends State<PaintDemo> | |
with SingleTickerProviderStateMixin { | |
late AnimationController _controller; | |
late CurvedAnimation _animation; | |
@override | |
void initState() { | |
_controller = | |
AnimationController(vsync: this, duration: const Duration(seconds: 3)); | |
_animation = CurvedAnimation(parent: _controller, curve: Curves.slowMiddle); | |
_controller.repeat(); | |
super.initState(); | |
} | |
@override | |
void dispose() { | |
_controller.dispose(); | |
super.dispose(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return AnimatedBuilder( | |
animation: _animation, | |
builder: (_, child) { | |
return CustomPaint( | |
painter: LinePainter(progress: _animation.value), | |
child: child, | |
); | |
}, | |
child: const SizedBox( | |
width: 200, | |
height: 75, | |
child: Text('Loading...'), | |
), | |
); | |
} | |
} | |
class LinePainter extends CustomPainter { | |
LinePainter({this.progress = 0.5}); | |
final double progress; | |
static final linePaint = Paint() | |
..color = const Color(0xFFF4AC45) | |
..style = PaintingStyle.stroke | |
..strokeWidth = 6 | |
..strokeCap = StrokeCap.round; | |
static const _gap = 12.0; | |
@override | |
void paint(Canvas canvas, Size size) { | |
final height = size.height / 2; | |
final widthProgress = size.width * progress; | |
final point1 = max(0.0, widthProgress - _gap); | |
final point2 = min(widthProgress + _gap, size.width); | |
canvas | |
..drawLine(Offset(0, height), Offset(point1, height), linePaint) | |
..drawLine(Offset(point2, height), Offset(size.width, height), linePaint); | |
} | |
@override | |
bool shouldRepaint(LinePainter oldDelegate) { | |
if (progress != oldDelegate.progress) { | |
return true; | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment