Last active
June 27, 2023 17:05
-
-
Save folaoluwafemi/8b99615deb3134410b793c38a438cc6c to your computer and use it in GitHub Desktop.
A simple but useful widget to implement animation, it provides a builder that exposes the current animation value, and calls the build method at every tick.
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 'package:flutter/widgets.dart'; | |
typedef CustomAnimationBuilderCallback = Widget Function( | |
BuildContext context, | |
double value, | |
Widget? child, | |
); | |
class CustomAnimationBuilder extends StatefulWidget { | |
final Duration duration; | |
final Widget? child; | |
final CustomAnimationBuilderCallback builder; | |
final AnimationBehavior animationBehavior; | |
final bool shouldRepeat; | |
const CustomAnimationBuilder({ | |
Key? key, | |
required this.duration, | |
required this.builder, | |
this.animationBehavior = AnimationBehavior.normal, | |
this.shouldRepeat = false, | |
this.child, | |
}) : super(key: key); | |
@override | |
State<CustomAnimationBuilder> createState() => _CustomAnimationBuilderState(); | |
} | |
class _CustomAnimationBuilderState extends State<CustomAnimationBuilder> | |
with SingleTickerProviderStateMixin { | |
late final AnimationController controller = AnimationController( | |
vsync: this, | |
duration: widget.duration, | |
lowerBound: 0, | |
upperBound: 1, | |
animationBehavior: AnimationBehavior.preserve, | |
); | |
late final Animation<double> animation; | |
@override | |
void initState() { | |
animation = Tween<double>(begin: 0, end: 1).animate( | |
controller, | |
); | |
if (widget.shouldRepeat) { | |
controller.repeat(); | |
} else { | |
controller.forward(); | |
} | |
super.initState(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return AnimatedBuilder( | |
animation: animation, | |
builder: (context, child) => widget.builder( | |
context, | |
animation.value, | |
child, | |
), | |
child: widget.child, | |
); | |
} | |
@override | |
void dispose() { | |
controller.dispose(); | |
super.dispose(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment