Learn how to build a simple Flutter counter app using setState for state management. Understand the fundamentals of stateful widgets and how setState triggers UI updates.
In this section, we will embark on a journey to build a simple yet fundamental Flutter application: a counter app. This app will serve as an introduction to state management using Flutter’s built-in setState
method. By the end of this tutorial, you will have a solid understanding of how to manage state in a Flutter application using setState
, and you’ll be equipped with the knowledge to extend this to more complex applications.
Before we dive into the code, let’s set up our Flutter project. Follow these steps to create a new Flutter project named counter_app
:
Open your terminal or command prompt.
Navigate to your desired directory where you want to create the project.
Run the following command to create a new Flutter project:
flutter create counter_app
Navigate into the project directory:
cd counter_app
Open the project in your preferred IDE (such as Visual Studio Code or Android Studio).
Our counter app will have a simple user interface consisting of:
Let’s start by designing the UI in main.dart
.
import 'package:flutter/material.dart';
void main() {
runApp(CounterApp());
}
class CounterApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Counter App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: CounterHomePage(),
);
}
}
class CounterHomePage extends StatefulWidget {
@override
_CounterHomePageState createState() => _CounterHomePageState();
}
class _CounterHomePageState extends State<CounterHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
void _decrementCounter() {
setState(() {
_counter--;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Counter App'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: _incrementCounter,
child: Text('Increment'),
),
SizedBox(width: 20),
ElevatedButton(
onPressed: _decrementCounter,
child: Text('Decrement'),
),
],
),
],
),
),
);
}
}
In the code above, we have implemented a StatefulWidget
called CounterHomePage
. This widget maintains the state of the counter. Let’s break down the key components:
State Variables: We declare an integer _counter
initialized to 0. This variable holds the current count.
setState Method: The setState
method is used to update the state of the widget. When the increment or decrement button is pressed, the _incrementCounter
or _decrementCounter
method is called, respectively. Inside these methods, setState
is invoked to update the _counter
variable and trigger a rebuild of the widget tree.
Let’s walk through the code to understand each part:
Main Function: The main
function is the entry point of the app. It calls runApp
with CounterApp
, which is a StatelessWidget
.
CounterApp Widget: This is a StatelessWidget
that sets up the MaterialApp
with a home page of CounterHomePage
.
CounterHomePage Widget: This is a StatefulWidget
that manages the state of the counter. It overrides createState
to return an instance of _CounterHomePageState
.
_CounterHomePageState Class: This class extends State<CounterHomePage>
and contains the state logic. It includes:
_counter
variable to hold the count._incrementCounter
and _decrementCounter
methods to modify the count.build
method to construct the UI, including a Scaffold
with an AppBar
and a Column
containing the text and buttons.To run the app and see it in action:
Ensure your emulator or physical device is connected.
Run the following command in your terminal:
flutter run
Interact with the app by pressing the increment and decrement buttons to see the counter update.
Below is a visual representation of how setState
triggers widget rebuilds:
graph TD; A[User Presses Button] --> B{setState Called} B -->|Yes| C[Update State Variable] C --> D[Rebuild Widget Tree] D --> E[UI Reflects New State]
This diagram illustrates the flow of operations when a button is pressed, leading to a call to setState
, which updates the state variable and rebuilds the widget tree to reflect the new state.
Here are some screenshots of the app in action:
Initial State:
After Increment:
After Decrement:
Building a counter app using setState
is a fundamental exercise in understanding state management in Flutter. This simple example lays the groundwork for more complex applications by demonstrating how to manage and update state within a StatefulWidget
. As you continue your journey in Flutter development, consider how setState
can be used in conjunction with other state management solutions to build robust and scalable applications.
For further exploration, consider experimenting with additional features such as resetting the counter, limiting the counter range, or persisting the counter value across app sessions.