Problem Statement
What are the best practices for using setState() in Flutter? What are common mistakes to avoid?
Explanation
Always update state variables inside the setState() callback function, not before calling it. This ensures Flutter knows exactly what changed and can optimize rebuilds accordingly. For example, setState(() => counter++); is correct, while counter++; setState(() {}); works but doesn't clearly indicate what changed and can confuse other developers.
Only call setState() when the change affects what build() returns. Don't call setState() for changes that don't impact UI, as it wastes resources triggering unnecessary rebuilds. Keep setState() callbacks small and fast, containing only state updates - never perform expensive operations like network requests or database queries inside setState() as it runs synchronously.
Always check if (mounted) before calling setState() in async callbacks, timers, or stream listeners to avoid errors when the widget is disposed while an async operation is in progress. This is one of the most common sources of bugs in Flutter apps. Never call setState() during build, initState (except in post-frame callbacks), or after dispose.
Avoid calling setState() on the entire widget when only a small part needs updating - consider breaking large widgets into smaller StatefulWidgets so only the affected parts rebuild. For complex state, consider state management solutions like Provider, Bloc, or Riverpod instead of managing everything with setState(). Use ValueNotifier for simple reactive state without rebuilding entire widgets.
