What is initState() used for?
initState() is called exactly once after the State object is inserted in the tree. Use it for one-time setup: loading data, subscribing to streams.
Master setState patterns, lifecycle methods and common pitfalls
You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.
Having trouble? AI is here to help
Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.
Use the AI button at the bottom of the screen
While setState is straightforward for basic local state, there are important nuances around lifecycle methods, async operations, and performance that every Flutter developer should understand to avoid common bugs.
1// ── StatefulWidget Lifecycle ──2class MyWidget extends StatefulWidget {3@override4State<MyWidget> createState() => _MyWidgetState();5}67class _MyWidgetState extends State<MyWidget> {89@override10void initState() {11super.initState(); // Always call super first!12// Initialize state, subscribe to streams, start timers13_loadData();14}1516@override17void didChangeDependencies() {18super.didChangeDependencies();19// Called after initState and when dependencies (InheritedWidget) change20}2122@override23void didUpdateWidget(MyWidget oldWidget) {24super.didUpdateWidget(oldWidget);25// Called when parent rebuilds with new widget config26if (widget.userId != oldWidget.userId) {27_loadData(); // reload when prop changes28}29}3031@override32void dispose() {33// CRITICAL: clean up resources to prevent memory leaks34_controller.dispose();35_subscription.cancel();36super.dispose(); // Always call super last!37}3839@override40Widget build(BuildContext context) {41return Container();42}43}
1// ── Safe async setState ──2bool _isMounted = true;34@override5void dispose() {6_isMounted = false;7super.dispose();8}910Future<void> _loadData() async {11final data = await api.fetchData();1213// Check if widget is still mounted before calling setState14if (mounted) { // Flutter provides built-in mounted checks15setState(() => _data = data);16}17}1819// ── Minimize setState scope ──20// BAD: rebuilds entire widget for one change21setState(() {22_isLoading = true;23_error = null;24doSomethingUnrelated(); // don't do this inside setState!25});2627// GOOD: only state mutations inside setState28_error = null; // can set this outside29setState(() => _isLoading = true); // only the part that triggers rebuild
If you call setState after await in an async method, the widget may have been removed from the tree. Use if (mounted) before setState in async methods to prevent the setState after dispose error.
Treat setState like a precision tool:
Clean setState usage improves frame stability and code readability.
Master setState patterns, lifecycle methods and common pitfalls. State is data that changes over time and controls what users see on the screen.
Connect each concept to real app features you can build.
Keep state as close as possible to where it is used, then lift it only when sharing is required.
State management is the difference between predictable apps and hard-to-debug UI behavior.
initState() is called exactly once after the State object is inserted in the tree. Use it for one-time setup: loading data, subscribing to streams.
The widget might be disposed before the async operation completes. Check `if (mounted)` before calling setState to prevent "setState after dispose" errors.
dispose() is called when the State is permanently removed. Use it to clean up: cancel timers, close streams, dispose controllers.
Something seems incorrect, unclear, or missing? Let us know.
FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.
Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.
Sign in to continue with exercises and quiz for this lesson.
Sign In to Continue