Create numbers that count-up and down with animations in Flutter

Flutter Jul 25, 2023

In this post, we go over the countup package for Flutter. It is a convenient tool that lets you add animated numbers to your applications. With countup, you can create cool count-up and down animations for displaying different types of information. Whether you want to show points in a game, statistics, or a countdown timer, this package has got you covered.

Installing

To get started with the implementation, we need to install the countup package into our project. The installation process is simple. Just execute the following command: flutter pub add countup.

Once the command is executed, make sure to check your pubspec.yaml file for the added dependencies. You should see the countup package included in the dependencies section, like this:

dependencies:
  countup: ^0.1.4
  flutter:
    sdk: flutter

Basic implementation

Here is a basic implementation of the countup package in Flutter. The goal is to create a simple count-up animation that starts from 0 and goes up to 9999.

import 'package:countup/countup.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Animated numbers demo',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Animated number'),
        ),
        body: Center(
          child: Countup(
            begin: 0,
            duration: Duration(seconds: 3),
            end: 9999,
            style: TextStyle(
              fontSize: 40,
            ),
          ),
        ),
      ),
    );
  }
}

In this code snippet, we start by importing the countup package and setting up the basic application structure using the MaterialApp and Scaffold widget.

Inside the Scaffold widget, we use the Countup widget to display the animated number. The Countup widget requires two properties:

  1. begin: This sets the starting value of the count-up animation, and in our case, it is 0.
  2. end: This property defines the target value where the animation should stop, which is 9999 in this example.

Additionally, we set the duration of the animation using the Duration class in the duration property. In this case, it is set to 3 seconds, overriding the default of 250 milliseconds which is a bit too fast.

We also styled the animated number using the style property, which takes a TextStyle widget. Which in this case is used, to increase the font size of the number.

When we run the application, you will see the number smoothly increasing from 0 to 9999, with a count-up animated effect.

flutter_animated_number_counting_up

Counting down

If you want to create a count-down animation, you can change the begin and end values. Here is an example of counting down from 9999 to 0 in 3 seconds:

Countup(
  begin: 9999,
  duration: Duration(seconds: 3),
  end: 0,
  style: TextStyle(
    fontSize: 40,
  ),
),

flutter_animated_number_counting_down

Animation

It is also possible to change the animation. This can be done by setting the curve property which has a default of Curves.linear. As done in the code below where we set the curve property to Curves.fastLinearToSlowEaseIn:

Countup(
  begin: 0,
  curve: Curves.fastLinearToSlowEaseIn,
  duration: Duration(seconds: 3),
  end: 9999,
  style: TextStyle(
    fontSize: 40,
  ),
),

flutter_animated_number_with_different_animation

Currencies

You can also use the countup package to display currencies with specific formatting. In this example, we count up from 0 to 100000 with the Euro (€) symbol as a prefix, a comma as a separator, and 2 decimal places:

Countup(
  begin: 0,
  duration: Duration(seconds: 3),
  end: 100000,
  prefix: '€ ',
  separator: ',',
  precision: 2,
  style: TextStyle(
    fontSize: 40,
  ),
),

flutter_animated_currency_counting_up

Transactions

For more complex implementations, such as dynamic transactions with interactive buttons, you can use the package like this:

import 'package:countup/countup.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  State createState() => _MyAppState();
}

class _MyAppState extends State {
  double begin = 1000;
  double end = 1000;
  bool isAnimating = false;

  void _handleUpdate(bool increment) {
    if (!isAnimating) {
      setState(() {
        if (increment) {
          end += 100;
        } else {
          end -= 100;
        }

        isAnimating = true;
      });

      Future.delayed(Duration(seconds: 3), () {
        setState(() {
          begin = end;
          isAnimating = false;
        });
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Animated numbers demo',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Animated number'),
        ),
        body: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
          Countup(
            begin: begin,
            duration: Duration(seconds: 3),
            end: end,
            prefix: '€ ',
            separator: ',',
            precision: 2,
            style: TextStyle(
              fontSize: 40,
            ),
          ),
          SizedBox(height: 10),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              IconButton(
                color: Colors.green,
                icon: Icon(Icons.add),
                onPressed: () => _handleUpdate(true)
              ),
              IconButton(
                color: Colors.red,
                icon: Icon(Icons.remove),
                onPressed: () => _handleUpdate(false),
              ),
            ],
          )
        ]),
      ),
    );
  }
}

In this code snippet, we made some changes to the MyApp widget to add a count-up and down animation. We turned the MyApp widget into a stateful widget, which allows it to keep track of changing values.

Inside the _MyAppState class, we added three variables, begin and end, which both start with a value of 1000 and isAnimating which is set to false. These variables will control the count-up and down animation.

The body of the Scaffold widget contains a Column widget, which organizes its children vertically. The first child of the Column widget is the Countup widget. We updated the Countup widget by using our begin and end variables as its properties.

After the Countup widget, we added a SizedBox widget to create some spacing. Then, we included a Row widget that displays two IconButton widgets. The IconButton widget with the add icon increases our number, while the IconButton widget with the remove icon decreases it.

When you press either button, the _handleIncrement function which is set on the onPressed property is triggered. Inside this function, we use the setState function, which updates the end value by adding or subtracting 100. This causes the user interface to rebuild, resulting in an animated count-up or down effect to the new end value over a 3-second duration.

After a 3-second delay, the begin value is also updated, to make sure that the new value is used for the next count-up or down animation when the user clicks the buttons again. To prevent the user from interfering with the animation, we use the isAnimating variable to temporarily disable the buttons.

flutter_adding_and_subtracting_from_number_with_animations

Conclusion

The countup package in Flutter helps you make cool animations that count up or down automatically. It is easy to use and great for showing numbers in a fun way, like in financial apps or statistics displays. You can customize the animations to match your requirements and make your application more enjoyable for users.

Tags