Flutter: `setState() called after dispose()` error
poze 5 months ago392 gadeen
6
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
Samuel Joseph 2.7k
Sign in and verify your email to post an answer.