0
0
Fluttermobile~5 mins

setState for local state in Flutter

Choose your learning style9 modes available
Introduction

We use setState to tell Flutter to update the screen when something changes in our app. It helps keep the app's look in sync with its data.

When you want to change a button label after it is pressed.
When you want to update a counter number on the screen after tapping.
When you want to show or hide a widget based on user action.
When you want to change colors or styles dynamically in response to user input.
Syntax
Flutter
setState(() {
  // update your local state variables here
});

setState takes a function where you update your variables.

Flutter will re-run the build method after setState to refresh the UI.

Examples
Increase a counter by 1 and update the screen.
Flutter
setState(() {
  counter = counter + 1;
});
Toggle a boolean to show or hide a widget.
Flutter
setState(() {
  isVisible = !isVisible;
});
Sample App

This app shows a number starting at 0. When you press the + button, it increases the number by 1. The screen updates because setState tells Flutter to rebuild the UI with the new number.

Flutter
import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: CounterScreen(),
    );
  }
}

class CounterScreen extends StatefulWidget {
  const CounterScreen({super.key});

  @override
  State<CounterScreen> 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: const Text('Counter Example')),
      body: Center(
        child: Text('Counter: $counter', style: const TextStyle(fontSize: 24)),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}
OutputSuccess
Important Notes

Always call setState inside a StatefulWidget class.

Do not put long or slow code inside setState to avoid UI delays.

Only update variables inside the function passed to setState.

Summary

setState updates local state and refreshes the UI.

Use it inside StatefulWidget to change what the user sees.

Keep the code inside setState simple and quick.