0
0
FlutterHow-ToBeginner · 3 min read

How to Use setState in Flutter: Simple Guide with Examples

In Flutter, use setState inside a StatefulWidget to update the UI when data changes. Call setState(() { ... }) with the code that modifies your state variables, and Flutter will rebuild the widget to reflect the changes.
📐

Syntax

The setState method takes a callback function where you update your state variables. Flutter then schedules a rebuild of the widget to show the new state.

  • setState(() { ... }): The callback where you change state.
  • Inside the callback: update variables that affect the UI.
  • After setState runs, Flutter calls build() again.
dart
setState(() {
  // update your state variables here
  counter = counter + 1;
});
💻

Example

This example shows a button that increases a counter. When pressed, setState updates the counter and the UI refreshes to show the new value.

dart
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 += 1;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Counter Example')),
      body: Center(
        child: Text('Counter: $counter', style: TextStyle(fontSize: 24)),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: incrementCounter,
        child: Icon(Icons.add),
      ),
    );
  }
}
Output
A screen with a title 'Counter Example', a text showing 'Counter: 0' initially, and a floating button with a plus icon. Each tap on the button increases the number displayed.
⚠️

Common Pitfalls

  • Calling setState without changing any state variables will still rebuild the widget but is inefficient.
  • Modifying state variables outside setState will not update the UI.
  • Do not call setState in the build() method or during widget construction; it causes infinite rebuilds.
  • Always keep state changes inside the setState callback to ensure proper UI updates.
dart
/* Wrong way: state changed outside setState, UI won't update */
void incrementWrong() {
  counter += 1; // state changed but no setState called
}

/* Right way: state changed inside setState */
void incrementRight() {
  setState(() {
    counter += 1;
  });
}
📊

Quick Reference

Remember these tips when using setState:

  • Use setState only in State classes of StatefulWidget.
  • Put all state changes inside the setState callback.
  • Keep setState calls minimal to avoid unnecessary rebuilds.
  • Do not call setState in build() or constructors.

Key Takeaways

Use setState inside StatefulWidget to update UI when state changes.
Always put state changes inside the setState callback function.
Avoid calling setState in build() or outside the State class.
setState triggers a widget rebuild to reflect new state values.
Keep setState calls minimal for better app performance.