How to create a counter in Flutter

Key takeaways:

  • With a single codebase, a rich ecosystem (pub package manager), and continuous open-source updates, Flutter simplifies cross-platform mobile and web development.

  • Flutter categorizes widgets as Stateless (immutable, e.g., Text, Image) and Stateful (mutable, e.g., TextField, Checkbox) to manage UI elements and interactivity effectively.

  • Choose from tools like Provider, Riverpod, Bloc/Cubit, and GetX based on application complexity and requirements to handle state changes and maintain scalability.

  • Counters are a common feature to dynamically increase or decrease values, implemented using methods like _incrementCounter and _decrementCounter, with UI updates managed via setState.

Flutter is a widely used user-interface framework to build mobile and web applications that are natively compiled. It provides creative freedom to the developers to create visually attractive applications by providing a variety of UI features. Flutter is among the highly preferred framework because of its features as follows:

  • Single codebase: One code set can be used across platforms like Android and iOS.

  • Rick ecosystem: Flutter has the pub package manager offering various packages and plugins.

  • Open source: Continuous bug fixing and new feature additions make it a powerful and up-to-date framework.

Widgets in flutter

Widgets refer to the components that are visible to the user, for example, text, buttons, images, and sliders. Flutter is a widgets-based framework that adds not only visual attributes but also manages the states, layout, and user-interactivity.

Type

Feature

Example

Stateless Widget

It has no mutable state.

text

image

Stateful Widget

It maintains a mutable state.

text field

checkbox

State management in Flutter

State management is one of the core concepts of Flutter, allowing developers to handle changes in state effectively. There are several ways to manage state in Flutter, each suited for different use cases. Some of the popular state management solutions are:

  • Provider: A lightweight state management tool that is easy to understand and implement, making it a good choice for small to medium-sized applications.

  • Riverpod: A more advanced version of Provider, offering better performance, testability, and safety features, making it suitable for complex applications.

  • Bloc/Cubit: Bloc (Business Logic Component) and Cubit are state management solutions that separate business logic from the UI, ensuring a clear and maintainable code structure.

  • GetX: A fast, powerful, and lightweight state management solution that also includes dependency injection and navigation capabilities.

Each of these solutions has its pros and cons, and the choice depends on the complexity of the application, developer preferences, and specific requirements. Understanding and applying the right state management technique is key to building scalable and maintainable Flutter applications.

What is a counter?

A counter is a dynamic feature to add or reduce the value. It is controlled by an increment and a decrement state which changes the value or quantity of the attribute updated with the state change.

Visual representation of a counter.
Visual representation of a counter.

Let's code this feature and make a small application in Flutter.

Example code

In this example, we make a simple counter that increases or decreases the value based on which button is clicked.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: CounterScreen(),
    );
  }
}

class CounterScreen extends StatefulWidget {
  @override
  _CounterScreenState createState() => _CounterScreenState();
}

class _CounterScreenState extends State<CounterScreen> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  void _decrementCounter() {
    setState(() {
      _counter--;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.purple,
      appBar: AppBar(
        title: Text('Aesthetic Counter'),
        backgroundColor: Colors.blue,
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            AnimatedOpacity(
              opacity: _counter != 0 ? 1.0 : 0.0,
              duration: Duration(milliseconds: 500),
              child: Text(
                '$_counter',
                style: TextStyle(
                  fontSize: 48.0,
                  color: Colors.white,
                ),
              ),
            ),
            SizedBox(height: 20.0),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                FloatingActionButton(
                  onPressed: _decrementCounter,
                  backgroundColor: Colors.blue,
                  child: Icon(Icons.remove),
                ),
                SizedBox(width: 20.0),
                FloatingActionButton(
                  onPressed: _incrementCounter,
                  backgroundColor: Colors.purple,
                  child: Icon(Icons.add),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
Create a counter.

Code explanation

  • Lines 1–4: Import the required packages and define the main by sending an instance of MyApp to the runApp() method.

  • Line 7: Define the MyApp class that extends the StatelessWidget class to access its methods and attributes.

  • Lines 9–11: Override the build method and return a MaterialApp and set the home property to CounterScreen().

  • Lines 16–18: Define the CounterScreen() class that extends the StatefulWidget class and create a _CounterScreenState() instance.

  • Line 21: Define the _CounterScreenState() class that represents the CounterScreen state.

  • Lines 24–26: Create an _incrementCounter() method that adds the value by 1 and calls the setState() method.

  • Lines 30–32: Create an _decrementCounter() method that subtracts the value by 1 and calls the setState() method.

  • Lines 37–38: Create the app UI in the build method that returns a Scaffold widget containing the basic structure.

  • Lines 40–42: Set the appBar property to an AppBar widget, which specifies the a title and the backgroundColor.

  • Lines 44–47: Set the body property to Center widget that contains the Column of child widgets.

  • Lines 48–55: Define the AnimatedOpacity widget that specifies the opacity and duration of the counter and a Text widget that specifies the text style, size, and color.

  • Lines 60–72: Align the two FloatingActionButton widgets in a Row that are used to increment and decrement the counter.

Code output

Press the increment and decrement buttons and see how the counter value changes by 1. If a decrement button is pressed when the value is zero, it displays negative values.


Real-life application

There are a lot of real-life applications that require a counter to add and remove instances and dynamically change the count. Let's look at a few of the scenarios where the counter is useful.

Real life application of a counter.
Real life application of a counter.

Conclusion

Flutter is a robust, flexible, and highly efficient framework for developing cross-platform applications, offering a single codebase that runs on both mobile and web platforms. Its widget-centric architecture simplifies UI design while providing extensive state management options to maintain dynamic and interactive applications. With its rich ecosystem, open-source nature, and constant updates, Flutter remains a preferred choice among developers. Whether building simple counters or complex, real-life applications, Flutter's comprehensive tools and libraries make it a powerful framework for creating visually appealing and responsive user interfaces

Further learning

Learn more about Flutter in the following Answers:

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is the Flutter counter plugin?

The Flutter Counter Plugin is a simple utility package that helps developers quickly add a counter feature to Flutter applications. Here are its key characteristics:

Purpose: It provides a pre-built counter component that can be easily integrated into Flutter apps to increment or decrement a numerical value.

Functionality: The plugin manages the basic logic for increasing or decreasing a counter’s value, making it ideal for use cases like item counting, score tracking, and more.

Customizability: Developers can customize the counter’s appearance, including button styles, colors, and layout, to align with the app’s design.

Ease of use: The plugin simplifies implementing counters, allowing developers to focus on other features without writing extensive logic from scratch.

This plugin serves as a convenient tool for adding counters in a wide range of Flutter applications, enhancing productivity and speeding up development.


How do you make a box in Flutter?

To create a box in Flutter, you can use the Container widget, which serves as a versatile tool for UI design. It allows you to define the box’s width, height, and color, making it customizable. You can further enhance the box by adding decorations like borders, shadows, and gradients using the decoration property. The Container also supports padding, margins, and alignment, making it suitable for holding other widgets such as text, images, or buttons. By adjusting these properties, you can create simple or complex box designs in your Flutter applications.


How can I create a table in Flutter?

In Flutter, you can create a table using the Table widget, which allows you to display data in rows and columns. It provides a structured layout where you can define the number of columns, rows, and cell contents. The Table widget is customizable, supporting alignment, padding, borders, and more, making it ideal for organizing data in a tabular format.

To populate the table, you use TableRow widgets to define each row, and the cells within each row can contain various widgets like text, images, or icons. The Table widget also offers properties like column width, default vertical alignment, and spacing to refine its layout according to your design needs.

The DataTable widget is another option, especially useful for displaying larger datasets with built-in features like sorting, pagination, and easy customization. This widget is best suited for apps with more complex data management requirements.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved