Flutter: `setState() called after dispose()` error

asked 5 months ago393 viewsen

6

When the user leaves a screen before an HTTP request finishes, I get setState() called after dispose(). How do I fix it properly?

AI diagnosis

AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.

asked 5 months ago

1 Answer

5
✓
✓ Accepted answer

The widget was removed from the tree while your async work was still running, and then its callback tried to update the dead widget.

Quick fix: check mounted after every await:

Future<void> _load() async {
  final data = await api.fetchItems();
  if (!mounted) return;
  setState(() => _items = data);
}

Better long-term: move async state out of widgets into a state-management layer (Riverpod, Bloc, or a ChangeNotifier). Those handle lifecycle and cancellation for you, and make the logic testable.

Also cancel what you own in dispose(): StreamSubscription.cancel(), controllers' dispose(), timers.

Sign in to tell others whether this worked.

answered 5 months ago

Sign in and verify your email to post an answer.