Timer callback called after widget dispose

setState() called after dispose(): Timer callback still active

Quick Answer

A Timer was not cancelled in dispose(), causing callbacks after the widget is removed.

Why This Happens

In Flutter, if you create a Timer or periodic timer in a State and do not cancel it in dispose(), the callback continues firing after the widget is removed. This leads to setState-after-dispose errors. Always cancel timers in the dispose method.

The Problem

class _MyState extends State<MyWidget> {
  late Timer _timer;

  @override
  void initState() {
    super.initState();
    _timer = Timer.periodic(Duration(seconds: 1), (_) {
      setState(() {});
    });
  }
  // Missing dispose!
}

The Fix

class _MyState extends State<MyWidget> {
  late Timer _timer;

  @override
  void initState() {
    super.initState();
    _timer = Timer.periodic(Duration(seconds: 1), (_) {
      setState(() {});
    });
  }

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

Step-by-Step Fix

  1. 1

    Identify the error

    Look at the setState-after-dispose error triggered by a Timer callback. The timer is still firing after the widget was removed.

  2. 2

    Find the cause

    Check if Timer or Timer.periodic instances are cancelled in the dispose() method of the State.

  3. 3

    Apply the fix

    Cancel all timers in the dispose() method to prevent callbacks from firing after the widget is removed.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free