Skip to content

Instantly share code, notes, and snippets.

@Hiteshpatel10
Last active March 6, 2024 07:50
Show Gist options
  • Save Hiteshpatel10/ed3ff1ebaa7d675373c90d17ffb84acd to your computer and use it in GitHub Desktop.
Save Hiteshpatel10/ed3ff1ebaa7d675373c90d17ffb84acd to your computer and use it in GitHub Desktop.
The CountingText widget in Flutter displays an animated text that counts from a specified beginning value to an end value. It utilizes an animation controller with a customizable curve and duration to animate the counting effect. Text style and other text properties can also be customized.
class CountingText extends StatefulWidget {
const CountingText({
Key? key,
required this.begin,
required this.end,
this.precision = 0,
this.curve = Curves.decelerate,
this.duration = const Duration(milliseconds: 400),
this.style,
this.textAlign,
this.textDirection,
this.locale,
this.softWrap,
this.overflow,
this.textScaleFactor,
this.maxLines,
this.semanticsLabel,
}) : super(key: key);
final double begin;
final double end;
final int precision;
final Curve curve;
final Duration duration;
final TextStyle? style;
final TextAlign? textAlign;
final TextDirection? textDirection;
final Locale? locale;
final bool? softWrap;
final TextOverflow? overflow;
final double? textScaleFactor;
final int? maxLines;
final String? semanticsLabel;
@override
CountingTextState createState() => CountingTextState();
}
class CountingTextState extends State<CountingText> with TickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _animation;
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
}
@override
void initState() {
super.initState();
_controller = AnimationController(duration: widget.duration, vsync: this);
CurvedAnimation curvedAnimation = CurvedAnimation(parent: _controller, curve: widget.curve);
_animation = Tween<double>(begin: widget.begin, end: widget.end).animate(curvedAnimation);
_controller.forward();
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _animation,
builder: (context, child) {
return Text(
_animation.value.toInt().toString(),
style: widget.style,
textAlign: widget.textAlign,
textDirection: widget.textDirection,
locale: widget.locale,
softWrap: widget.softWrap,
overflow: widget.overflow,
textScaleFactor: widget.textScaleFactor,
maxLines: widget.maxLines,
semanticsLabel: widget.semanticsLabel,
);
},
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment