State management helps your app remember and update information on the screen. It keeps your app working smoothly when things change.
0
0
State management comparison in Flutter
Introduction
When you want to update the screen after a button press.
When you need to share data between different parts of your app.
When your app has forms or inputs that change over time.
When you want to keep track of user login status.
When you want to handle data from the internet and show it on the screen.
Syntax
Flutter
class MyWidget extends StatefulWidget { @override State<MyWidget> createState() => _MyWidgetState(); } class _MyWidgetState extends State<MyWidget> { int counter = 0; void increment() { setState(() { counter++; }); } @override Widget build(BuildContext context) { return Text('Count: $counter'); } }
setState() tells Flutter to update the screen with new data.
State can be local (inside one widget) or shared (across many widgets).
Examples
Simple local state update inside a StatefulWidget.
Flutter
int counter = 0; void increment() { setState(() { counter++; }); }
Example of global state using Riverpod package.
Flutter
final counterProvider = StateProvider<int>((ref) => 0); // Using Riverpod to manage state globally.
Provider with ChangeNotifier to notify widgets when data changes.
Flutter
class CounterModel extends ChangeNotifier { int _count = 0; int get count => _count; void increment() { _count++; notifyListeners(); } } // Using Provider package with ChangeNotifier.
Sample App
This app shows a number on the screen. When you press the + button, the number goes up. It uses local state inside a StatefulWidget.
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 MaterialApp( home: CounterScreen(), ); } } class CounterScreen extends StatefulWidget { @override State<CounterScreen> createState() => _CounterScreenState(); } class _CounterScreenState extends State<CounterScreen> { int _count = 0; void _increment() { setState(() { _count++; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Counter Example')), body: Center( child: Text('Count: $_count', style: const TextStyle(fontSize: 24)), ), floatingActionButton: FloatingActionButton( onPressed: _increment, child: const Icon(Icons.add), tooltip: 'Increment', ), ); } }
OutputSuccess
Important Notes
Local state with setState() is simple but only works inside one widget.
For bigger apps, use packages like Provider, Riverpod, or Bloc to share state easily.
Choose state management based on app size and complexity.
Summary
State management keeps your app data and UI in sync.
Use setState() for small, local changes.
Use Provider, Riverpod, or Bloc for bigger apps with shared data.