Understand setState, InheritedWidget, and when to use each.
State Management Overview
Flutter offers several state management approaches:
| Approach | Complexity | Best For | Learning Curve |
|---|---|---|---|
setState | Low | Simple, local state | Easy |
InheritedWidget | Medium | Theme, locale, auth | Medium |
Provider | Medium | App-wide state | Easy |
Riverpod | Medium-High | Scalable, testable | Medium |
Bloc/Cubit | High | Complex business logic | Steep |
setState - Local Component State
setState is the simplest way to manage state within a single widget.
class CounterWidget extends StatefulWidget {
@override
State<CounterWidget> createState() => _CounterWidgetState();
}
class _CounterWidgetState extends State<CounterWidget> {
int _count = 0;
void _increment() {
setState(() {
_count++;
});
}
@override
Widget build(BuildContext context) {
return Column(
children: [
Text('Count: $_count', style: TextStyle(fontSize: 24)),
ElevatedButton(onPressed: _increment, child: Text('Increment')),
],
);
}
}When setState Works Well
- ✅ Simple UI state (toggles, counters, form inputs)
- ✅ State doesn't need to be shared
- ✅ Few or simple rebuilds
- ✅ Learning Flutter basics
setState Limitations
// PROBLEM: State stuck in leaf widget
class Parent extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
children: [
ChildA(), // Needs count
ChildB(), // Needs count
ChildC(), // Needs to modify count
],
);
}
}
// SOLUTION 1: Lift state up (but causes rebuilds)
class Parent extends StatefulWidget {
@override
State<Parent> createState() => _ParentState();
}
class _ParentState extends State<Parent> {
int _count = 0;
@override
Widget build(BuildContext context) {
return Column(
children: [
ChildA(count: _count), // Rebuilds when count changes
ChildB(count: _count), // Rebuilds when count changes
ChildC(onIncrement: () => setState(() => _count++)), // Rebuilds
],
);
}
}
// PROBLEM: Unnecessary rebuilds of ChildA and ChildBInheritedWidget - Efficient Data Propagation
InheritedWidget allows data to flow down the widget tree efficiently - only widgets that depend on the data rebuild when it changes.
// Data holder
class CounterModel extends InheritedWidget {
final int count;
final VoidCallback increment;
const CounterModel({
super.key,
required super.child,
required this.count,
required this.increment,
});
// Called when CounterModel updates
@override
bool updateShouldNotify(CounterModel oldWidget) {
return count != oldWidget.count;
}
// Convenience method to access from context
static CounterModel? of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<CounterModel>();
}
}
// Provider widget (wraps app)
class CounterProvider extends StatefulWidget {
final Widget child;
const CounterProvider({super.key, required this.child});
@override
State<CounterProvider> createState() => _CounterProviderState();
}
class _CounterProviderState extends State<CounterProvider> {
int _count = 0;
void _increment() => setState(() => _count++);
@override
Widget build(BuildContext context) {
return CounterModel(
count: _count,
increment: _increment,
child: widget.child,
);
}
}
// Consumers - only rebuild when count changes
class DisplayCount extends StatelessWidget {
@override
Widget build(BuildContext context) {
final model = CounterModel.of(context)!;
return Text('Count: ${model.count}', style: TextStyle(fontSize: 24));
}
}
class IncrementButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
final model = CounterModel.of(context)!;
return ElevatedButton(
onPressed: model.increment,
child: Text('Increment'),
);
}
}
// Usage
void main() {
runApp(
CounterProvider(
child: MaterialApp(
home: Scaffold(
body: Column(
children: [
DisplayCount(), // Rebuilds on count change
IncrementButton(), // Never rebuilds (no dependency)
OtherWidget(), // Never rebuilds
],
),
),
),
),
);
}InheritedWidget Pattern
┌─────────────────────────────────────────────────────────┐
│ CounterProvider │
│ (StatefulWidget - holds state, rebuilds on change) │
└──────────────────────────┬──────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ CounterModel │
│ (InheritedWidget - notifies dependents on change) │
└──────────────────────────┬──────────────────────────────┘
│
┌───────────────┼───────────────┐
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│Display │ │Increment │ │Other │
│Count │ │Button │ │Widget │
│(depends) │ │(depends) │ │(ignores) │
└──────────┘ └──────────┘ └──────────┘
✓ Rebuild ✓ Rebuild ✗ No rebuild
InheritedWidget Variants
InheritedModel - Fine-grained Dependencies
class UserProfileModel extends InheritedModel<UserProfileAspect> {
final String name;
final String email;
final String avatar;
const UserProfileModel({
super.key,
required super.child,
required this.name,
required this.email,
required this.avatar,
});
@override
bool updateShouldNotify(UserProfileModel oldWidget) {
return name != oldWidget.name ||
email != oldWidget.email ||
avatar != oldWidget.avatar;
}
@override
bool updateShouldNotifyDependent(
UserProfileModel oldWidget,
Set<UserProfileAspect> aspects
) {
if (aspects.contains(UserProfileAspect.name) && name != oldWidget.name) {
return true;
}
if (aspects.contains(UserProfileAspect.email) && email != oldWidget.email) {
return true;
}
if (aspects.contains(UserProfileAspect.avatar) && avatar != oldWidget.avatar) {
return true;
}
return false;
}
static UserProfileModel? of(BuildContext context, {UserProfileAspect? aspect}) {
return aspect != null
? context.dependOnInheritedWidgetOfExactType<UserProfileModel>(
aspect: aspect
)
: context.dependOnInheritedWidgetOfExactType<UserProfileModel>();
}
}
enum UserProfileAspect { name, email, avatar }
// Usage - only rebuilds when specific aspect changes
class NameDisplay extends StatelessWidget {
@override
Widget build(BuildContext context) {
final model = UserProfileModel.of(context, aspect: UserProfileAspect.name)!;
return Text(model.name);
}
}InheritedNotifier - With Listenable
class CounterNotifier extends ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
class CounterInheritedNotifier extends InheritedNotifier<CounterNotifier> {
const CounterInheritedNotifier({
super.key,
required super.notifier,
required super.child,
});
static CounterNotifier of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<CounterInheritedNotifier>()!.notifier;
}
}
// Usage
class CounterProvider extends StatelessWidget {
final Widget child;
const CounterProvider({super.key, required this.child});
@override
Widget build(BuildContext context) {
return CounterInheritedNotifier(
notifier: CounterNotifier(),
child: child,
);
}
}
// Consumer
class DisplayCount extends StatelessWidget {
@override
Widget build(BuildContext context) {
final notifier = CounterInheritedNotifier.of(context);
// Rebuilds on notifyListeners()
return Text('Count: ${notifier.count}');
}
}ChangeNotifier - Observable Pattern
import 'package:flutter/foundation.dart';
class MovieViewModel extends ChangeNotifier {
List<Movie> _movies = [];
bool _isLoading = false;
String? _error;
List<Movie> get movies => _movies;
bool get isLoading => _isLoading;
String? get error => _error;
Future<void> loadMovies() async {
_isLoading = true;
_error = null;
notifyListeners();
try {
_movies = await MovieRepository.fetchAll();
} catch (e) {
_error = e.toString();
} finally {
_isLoading = false;
notifyListeners();
}
}
void addMovie(Movie movie) {
_movies = [..._movies, movie];
notifyListeners();
}
}When to Use What
| Scenario | Solution |
|---|---|
| Single widget toggle | setState |
| Form with few fields | setState |
| Theme/locale/auth data | InheritedWidget |
| App-wide simple state | Provider (wraps InheritedWidget) |
| Complex async state | ChangeNotifier + Provider |
| Scalable, testable state | Riverpod / Bloc |
Migration Path
setState (local)
↓
Lift state up (parent setState)
↓
InheritedWidget (efficient propagation)
↓
Provider (simpler API for InheritedWidget)
↓
Riverpod/Bloc (advanced features)
Try It
Build a counter with 3 levels: Provider → Display → Button. Compare rebuilds using debugPrint in build methods.
class DebugWidget extends StatelessWidget {
final String name;
const DebugWidget(this.name, {super.key});
@override
Widget build(BuildContext context) {
debugPrint('$name rebuilt');
return Text(name);
}
}Implement theme with InheritedWidget
- Create ThemeModel extends InheritedWidget with brightness, colorScheme
- Create ThemeProvider StatefulWidget
- Build widgets that consume theme (AppBar, Card, Button)
- Add toggle button to switch light/dark
- Verify only themed widgets rebuild
setState is for local widget state. InheritedWidget efficiently propagates data down the tree - only dependents rebuild. ChangeNotifier adds observable pattern. These are building blocks; Provider/Riverpod/Bloc provide better APIs for real apps.
Resources
- InheritedWidget: https://api.flutter.dev/flutter/widgets/InheritedWidget-class.html
- ChangeNotifier: https://api.flutter.dev/flutter/foundation/ChangeNotifier-class.html
- State Management Intro: https://docs.flutter.dev/data-and-backend/state-mgmt/intro