You start an async call (network, timer), the user navigates away, the widget is disposed — then the call finishes and tries to setState on a dead widget. Flutter throws. The fix is to check mounted.
The Error
setState() called after dispose(): This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree.
Fix 1: Guard With mounted
Future<void> _load() async {
final data = await api.fetch();
if (!mounted) return; // widget gone? bail out
setState(() => _data = data);
}Fix 2: Cancel Subscriptions and Timers in dispose
StreamSubscription? _sub;
Timer? _timer;
@override
void dispose() {
_sub?.cancel();
_timer?.cancel();
super.dispose();
}Better: Move State Out of the Widget
With Riverpod or Bloc, async state lives outside the widget lifecycle, so a disposed screen can't crash a pending request. This class of bug disappears entirely.
