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

posée 5 months ago395 vuesen

6

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

Diagnostic IA

Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.

posée 5 months ago

1 réponse

5
✓
✓ Réponse acceptée

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.

Connectez-vous pour dire si ça a marché.

answered 5 months ago

Sign in and verify your email to post an answer.