DEV Community

Cover image for šŸš€ Flutter State Management 101: Building an Interactive Counter
Flutter Sensei
Flutter Sensei

Posted on • Originally published at fluttersensei.com

šŸš€ Flutter State Management 101: Building an Interactive Counter

Ever wondered why updating a variable in your Flutter code doesn't automatically update the screen? It's a classic roadblock for beginners.

Let's break down the fundamentals of State and setState() by looking at a minimal, interactive counter application.

The Problem: Background Memory vs. The Screen

If you directly update a private variable inside a button's onPressed block like this:

onPressed: () {
  _counter++; // Quietly changes the value in memory
  print(_counter); // Prints 1, 2, 3... in the console
}

Enter fullscreen mode Exit fullscreen mode

The data changes in the phone's memory, but your screen stays frozen at 0. Why? Because Flutter has no idea a change occurred, so it never re-runs the build() method to redraw the UI.


The Solution: Understanding setState()

To sync your data with your UI, you must use setState(). This built-in function acts as an explicit alarm system for a StatefulWidget, instructing Flutter to immediately repaint the screen with the fresh data.

Here is how you implement it cleanly across your interaction controls:

1. Increment

ElevatedButton.icon(
  onPressed: () {
    setState(() => _counter++);
  },
  icon: const Icon(Icons.add),
  label: const Text('Increment'),
)

Enter fullscreen mode Exit fullscreen mode

2. Decrement (With a Safety Guard)

ElevatedButton.icon(
  onPressed: () {
    if (_counter > 0) {
      setState(() => _counter--);
    }
  },
  icon: const Icon(Icons.remove),
  label: const Text('Decrement'),
)

Enter fullscreen mode Exit fullscreen mode

3. Reset

ElevatedButton.icon(
  onPressed: () {
    setState(() => _counter = 0);
  },
  icon: const Icon(Icons.refresh),
  label: const Text('Reset'),
)

Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  • State is any live data in your app that can change over time while a user interacts with it.
  • setState() is mandatory whenever you change a state variable that the user interface depends on.
  • Performance Tip: Always use the const keyword on static layouts (Padding, SizedBox, static Text) to prevent unnecessary UI redraws and keep your application executing at a smooth 60 or 120 FPS.

šŸ“– Read the Full Step-by-Step Tutorial

This is just the surface! Want to see the complete, performance-optimized layout files, folder structures, and step-by-step widget configurations?

Read the Full Step-by-Step Tutorial!

Flutter State Management Basics | Flutter Sensei

Learn Flutter State Management for beginners by building a simple Counter App and understanding how setState updates the UI.

favicon fluttersensei.com

Top comments (0)