---
title: "How do you fix \"setState() called after dispose()\" in Flutter?"
description: "An async callback finished after the widget left the tree. Check mounted before setState and cancel timers, listeners and streams in dispose()."
url: "https://bugsee.com/answers/flutter/fix-setstate-called-after-dispose/"
---

# How do you fix "setState() called after dispose()" in Flutter?

The widget was removed before an async task finished. Check `mounted` before calling `setState`, and cancel timers, listeners and subscriptions in `dispose()`.

```dart
class _ProfileState extends State<Profile> {
  String? name;
  late final StreamSubscription sub;

  @override
  void initState() {
    super.initState();
    sub = userStream.listen((u) {
      if (!mounted) return;
      setState(() => name = u.name);
    });
  }

  Future<void> load() async {
    final user = await api.fetchUser();
    if (!mounted) return;            // the user may have left the screen
    setState(() => name = user.name);
  }

  @override
  void dispose() {
    sub.cancel();                    // stop callbacks reaching a dead widget
    super.dispose();
  }
}
```

The `mounted` check silences the symptom, while cancelling in `dispose()` fixes the cause for long-lived sources like streams and timers. For state that should survive screen changes, move it out of the widget into a state management solution.

## Related questions

- [How do you fix "Null check operator used on a null value" in Flutter?](https://bugsee.com/answers/flutter/fix-null-check-operator-used-on-a-null-value/)
