StatefulWidget Lifecycle & Resource Cleanup
Master the 7-stage lifecycle of Flutter's State class. Learn when to initialize streams, respond to parent updates with didUpdateWidget, observe operating system lifecycle states, and guarantee leak-free cleanup in dispose.
1. The 7-Stage State Lifecycle Pipeline
When a StatefulWidget enters and leaves the widget tree, its associated State instance undergoes a strictly defined lifecycle managed by the StatefulElement.
2. Deep Dive: Lifecycle Method Responsibilities
| Lifecycle Hook | Invocation Timing | Allowed Operations | Forbidden Operations |
|---|---|---|---|
createState() | When StatefulWidget is mounted. | Instantiate State class. | Heavy logic or async operations. |
initState() | Once per State lifetime after creation. | Initialize controllers, subscribe to streams, start timers, setup non-context listeners. | Calling InheritedWidget via context.dependOnInheritedWidgetOfExactType (context not fully wired). |
didChangeDependencies() | Right after initState(), and whenever an ancestor InheritedWidget changes. | Reading Theme.of(context), MediaQuery.of(context), initializing context-dependent resources. | Heavy computational tasks that block rendering. |
build() | On initial mount, setState(), or ancestor rebuild. | Pure declarative UI creation returning a Widget. | Triggering side-effects, starting HTTP calls, or mutating state. |
didUpdateWidget() | Whenever parent widget rebuilds and provides a new widget instance with identical runtimeType and key. | Comparing oldWidget properties against widget to restart animations or update internal caches. | Forgetting to check if (oldWidget.id != widget.id). |
deactivate() | When Element is temporarily unlinked from tree (e.g. during GlobalKey reparenting). | Cleanup temporary hooks if reparenting. | Assuming the widget is permanently destroyed. |
dispose() | When Element is permanently destroyed and unmounted. | Disposing controllers, canceling stream subscriptions, closing sinks. | Calling setState() (throws StateError). |
3. Production Resource Cleanup Template
Failing to dispose controllers and subscriptions leads to severe memory leaks where orphaned callbacks continue running in the background.
class ProductionDataFeedScreen extends StatefulWidget {
final String channelId;
const ProductionDataFeedScreen({required this.channelId, super.key});
@override
State<ProductionDataFeedScreen> createState() => _ProductionDataFeedScreenState();
}
class _ProductionDataFeedScreenState extends State<ProductionDataFeedScreen>
with SingleTickerProviderStateMixin {
late final TextEditingController _textController;
late final ScrollController _scrollController;
late final AnimationController _animController;
StreamSubscription<dynamic>? _feedSubscription;
@override
void initState() {
super.initState();
// 1. Initialize local controllers
_textController = TextEditingController();
_scrollController = ScrollController();
_animController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 400),
);
// 2. Start data stream subscription
_subscribeToChannel(widget.channelId);
}
void _subscribeToChannel(String channelId) {
_feedSubscription?.cancel();
_feedSubscription = MockEventBus.stream(channelId).listen((event) {
if (mounted) { // β‘ Always check mounted before calling setState in callbacks
setState(() {});
}
});
}
@override
void didUpdateWidget(covariant ProductionDataFeedScreen oldWidget) {
super.didUpdateWidget(oldWidget);
// 3. React to parent parameter updates
if (oldWidget.channelId != widget.channelId) {
_subscribeToChannel(widget.channelId);
}
}
@override
void dispose() {
// 4. MANDATORY: Clean up every single resource in reverse order
_feedSubscription?.cancel();
_textController.dispose();
_scrollController.dispose();
_animController.dispose();
super.dispose(); // Always call super.dispose() last
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(controller: _scrollController, children: const []),
);
}
}4. App Lifecycle Tracking (WidgetsBindingObserver)
To pause video playback, save unsaved state, or refresh auth tokens when the user backgrounds the mobile app:
class AppStateTracker extends StatefulWidget {
const AppStateTracker({super.key});
@override
State<AppStateTracker> createState() => _AppStateTrackerState();
}
class _AppStateTrackerState extends State<AppStateTracker>
with WidgetsBindingObserver {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this); // Register observer
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this); // Unregister observer
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
switch (state) {
case AppLifecycleState.resumed:
print("π± App is visible and interactive");
break;
case AppLifecycleState.inactive:
print("βΈοΈ App is transitioning (e.g. phone call / notification drawer)");
break;
case AppLifecycleState.paused:
print("π App is in background (not visible)");
break;
case AppLifecycleState.detached:
print("π Flutter engine is still running but detached from view");
break;
case AppLifecycleState.hidden:
print("ποΈ App is hidden by OS window manager");
break;
}
}
@override
Widget build(BuildContext context) => const Placeholder();
}β Knowledge Check
Why does calling setState() inside dispose() throw a Flutter runtime exception?
What is the purpose of the didUpdateWidget(covariant T oldWidget) lifecycle method?
Stateless vs. Stateful Widgets & BuildContext
Understand the structural mechanics of StatelessWidget vs. StatefulWidget, why StatefulWidget is split into two classes, and the deep identity of BuildContext as an Element handle in the tree.
BoxConstraints & Layout Protocol
Master Flutter's core layout axiom: Constraints go down, Sizes go up, Parent positions child. Understand tight vs. loose vs. unbounded constraints, and solve yellow-and-black stripe RenderFlex overflow errors.