Animated Counter
Loading preview
Starting the Flutter app
Number roll/slide effect with AnimatedSwitcher
import 'package:flutter/material.dart';
class AnimatedCounter extends StatefulWidget {
const AnimatedCounter({super.key});
@override
State<AnimatedCounter> createState() => _AnimatedCounterState();
}
class _AnimatedCounterState extends State<AnimatedCounter> {
var _count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Animated Counter')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
AnimatedSwitcher(
duration: const Duration(milliseconds: 300),
transitionBuilder: (child, animation) => SlideTransition(
position: Tween<Offset>(
begin: const Offset(0, -1),
end: Offset.zero,
).animate(animation),
child: FadeTransition(
opacity: animation,
child: child,
),
),
child: Text(
'$_count',
key: ValueKey(_count),
style: Theme.of(context).textTheme.displayLarge,
),
),
const SizedBox(height: 24),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton.filled(
tooltip: 'Decrease',
onPressed: () => setState(() => _count--),
icon: const Icon(Icons.remove),
),
const SizedBox(width: 16),
IconButton.filled(
tooltip: 'Increase',
onPressed: () => setState(() => _count++),
icon: const Icon(Icons.add),
),
],
),
],
),
),
);
}
}
Add it to your project
Copies the Dart source into your app, so you own it. Flutter SDK only, no extra packages.
First time? Run dart pub global activate fluttertemplates_dev, or read the CLI guide.
How it works
AnimatedSwitcher does the work: ValueKey(_count) tells it each number is a new child, and transitionBuilder combines a SlideTransition from above with a FadeTransition over 300 ms. The outgoing number plays the same transition in reverse. Direction is fixed, so decrementing slides the same way as incrementing, and _count has no lower limit.
Adapting it
- Extract the
AnimatedSwitcherinto a widget that takes a value, for cart totals and the like. - To flip direction on decrement, keep the previous value and pick the
Tweenbeginoffset from it. - Clamp the
_count--handler if negative numbers make no sense for your screen.