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

poze 5 months ago391 gadeen

6

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

Dyagnostik IA

Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.

poze 5 months ago

1 Repons

5
✓
✓ Repons yo aksepte

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.

Konekte pou di lòt moun si li te mache.

answered 5 months ago

Sign in and verify your email to post an answer.