Google Advertisement

Simple Flutter Counter App Tutorial Using setState() for Beginners

Google Advertisement
πŸ”₯ Read with Full Features on Our Website

Learn how to build a basic counter app in Flutter using setState() for state management. A step-by-step beginner-friendly tutorial with code and explanation.

Published on 04 May 2025
By Vandu

Create a Counter App Using setState() in Flutter – Step-by-Step Guide

If you're just getting started with Flutter, one of the best ways to learn is by building simple apps. In this tutorial, we'll build a Counter App using setState(), which is the most basic form of state management in Flutter.

πŸ”₯ Read with Full Features on Our Website

By the end of this guide, you’ll understand:


βœ… What is setState() in Flutter?

In Flutter, setState() is used to tell the framework that the state of the app has changed. It allows your app to rebuild the UI when something changes — like when a user clicks a button.

Whenever you call setState(), Flutter knows it needs to re-render the widget so that it can display the new data.


πŸ› οΈ Prerequisites

Before we start coding, make sure you have the following installed:


πŸš€ Step-by-Step: Create a Counter App

1️⃣ Step 1: Create a New Flutter Project

Open your terminal or command prompt and run:

flutter create counter_app

Navigate to the newly created folder:

cd counter_app

Open the project in your code editor (VS Code or Android Studio).


2️⃣ Step 2: Replace the main.dart File

Open lib/main.dart and replace its contents with the following code:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Counter App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: CounterPage(),
    );
  }
}

class CounterPage extends StatefulWidget {
  @override
  _CounterPageState createState() => _CounterPageState();
}

class _CounterPageState extends State<CounterPage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++; // Increase the counter value by 1
    });
  }

  void _decrementCounter() {
    setState(() {
      _counter--; // Decrease the counter value by 1
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Counter App using setState()'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Current Counter Value:',
              style: TextStyle(fontSize: 20),
            ),
            Text(
              '$_counter',
              style: TextStyle(fontSize: 40, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 30),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ElevatedButton(
                  onPressed: _incrementCounter,
                  child: Text('Increment'),
                ),
                SizedBox(width: 20),
                ElevatedButton(
                  onPressed: _decrementCounter,
                  child: Text('Decrement'),
                ),
              ],
            )
          ],
        ),
      ),
    );
  }
}

🧠 Explanation of the Code

Let’s break it down step-by-step:

➀ main() function

This is the entry point of the Flutter app. It runs the MyApp widget.

➀ MyApp Widget

Google Advertisement

A stateless widget that sets up the MaterialApp, which includes the app's theme and the home page (CounterPage).

➀ CounterPage Widget

A stateful widget that manages the counter logic. We use a StatefulWidget because we need to change and track the counter value dynamically.

➀ _counter Variable

An integer that stores the current count. It starts at 0.

➀ _incrementCounter() and _decrementCounter() Methods

These methods call setState(), which tells Flutter to rebuild the UI with the updated counter value.

➀ build() Method

This builds the UI. It shows the current counter and two buttons — one to increase and another to decrease the counter.


πŸ“± Output: What Will You See?

When you run the app, you'll see:

Google Advertisement

Tapping the buttons updates the number in real time, thanks to setState().


πŸ”„ Why Use setState()?

However, for large apps or complex state logic, you'll want to explore more advanced options like Provider, Riverpod, or Bloc.


πŸ§ͺ Pro Tips


🎯 Conclusion

Building a Flutter Counter App using setState() is a great way to get comfortable with state management basics. This foundational concept is essential for all Flutter developers.

As you continue learning, try converting this app into one that uses other state management solutions to compare how they work.

❀️ Like πŸ’¬ Comment πŸ”— Share
Google Advertisement
πŸ‘‰ View Full Version on Main Website β†—
Google Advertisement
πŸ‘‰ Read Full Article on Website