Programming Errors & Bugs
Open
Example from the ReviewMyCodes team
Flutter: "setState() called after dispose()" when an API call finishes
Description
My Flutter screen loads data from an API in initState. If the user leaves the screen before the request finishes, the app logs an error and sometimes the next screen behaves strangely.
— This is an example problem from the ReviewMyCodes team, showing how a good question looks. Real community questions appear alongside it.
Expected
Leaving the screen early should simply cancel or ignore the late response.
Actual
FlutterError: setState() called after dispose(): _ProfileScreenState#1a2b3(lifecycle state: defunct, not mounted)
Steps to reproduce
- Open the Profile screen
- Press back before the data appears
- Watch the debug console
Code
dart
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
final data = await api.fetchProfile();
setState(() => _profile = data); // crashes if the screen is gone
}