Back to Blog
Bug Fixes•1 min read

Fix Flutter 'setState() called after dispose()'

Scaleup Infotech Team
Scaleup Infotech Team

Custom Software & Business Automation

FlutterStateAsyncLifecycle

In this guide

A simple guide to this issue: Flutter 'setState() called after dispose()'. Learn why it happens, what to check first, and how to fix it.

You start an async call (network, timer), the user navigates away, the widget is disposed — then the call finishes and tries to setState on a dead widget. Flutter throws. The fix is to check mounted.

The Error

setState() called after dispose(): This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree.

Fix 1: Guard With mounted

dart
Future<void> _load() async {
  final data = await api.fetch();
  if (!mounted) return;       // widget gone? bail out
  setState(() => _data = data);
}

Fix 2: Cancel Subscriptions and Timers in dispose

dart
StreamSubscription? _sub;
Timer? _timer;

@override
void dispose() {
  _sub?.cancel();
  _timer?.cancel();
  super.dispose();
}

Better: Move State Out of the Widget

With Riverpod or Bloc, async state lives outside the widget lifecycle, so a disposed screen can't crash a pending request. This class of bug disappears entirely.

Relevant Scaleup Infotech Services

Share this article:

Keep Reading

Ready to implement these ideas?

Discuss Your Project