Skip to content

Better error description and better docs for State.dispose #148031

Closed

Description

@FMorschel

Use case

I've stumbled upon #64935 today.

Here is a reproducible code
import 'package:flutter/material.dart';

bool show = true;

void main() => runApp(
      MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: const Text('Example'),
          ),
          body: StatefulBuilder(
            builder: (context, setState) {
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    FilledButton(
                      child: Text('Toggle'),
                      onPressed: () => setState(() => show = !show),
                    ),
                    if (show) DisposeErrorExample(),
                  ],
                ),
              );
            },
          ),
        ),
      ),
    );

class DisposeErrorExample extends StatefulWidget {
  const DisposeErrorExample({super.key});

  @override
  State<DisposeErrorExample> createState() => _DisposeErrorExampleState();
}

class _DisposeErrorExampleState extends State<DisposeErrorExample> {
  @override
  void dispose() async {
    debugPrint('Disposing');
    await Future.delayed(const Duration(milliseconds: 1));
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 50,
      height: 50,
      child: ColoredBox(
        color: Theme.of(context).primaryColor,
      ),
    );
  }
}

Here is what we get ruining after we press the button:

══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following assertion was thrown while finalizing the widget tree:
_DisposeErrorExampleState.dispose failed to call super.dispose.
dispose() implementations must always call their superclass dispose() method, to ensure that all the
resources used by the widget are fully released.

Proposal

I propose two changes.

When running async methods on setState there is already a test for asynchronous code, so the same logic could maybe be applied here to output a better error message to the user.

Code and output for async code on `setState`

Output:

══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
The following assertion was thrown while handling a gesture:
setState() callback argument returned a Future.
The setState() method on _StatefulBuilderState#00793 was called with a closure or method that
returned a Future. Maybe it is marked as "async".
Instead of performing asynchronous work inside a call to setState(), first execute the work (without
updating the widget state), and then synchronously update the state inside a call to setState().

Code:

import 'package:flutter/material.dart';

void main() => runApp(
      MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: const Text('Example'),
          ),
          body: StatefulBuilder(
            builder: (context, setState) {
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    FilledButton(
                      child: Text('Toggle'),
                      onPressed: () => setState(
                        () async => await Future.delayed(
                          const Duration(milliseconds: 1),
                        ),
                      ),
                    ),
                  ],
                ),
              );
            },
          ),
        ),
      ),
    );

An easier task I believe would be to add some reference to this on State.dispose docs. Telling what is the preferred way to solve that, if there is one. In the mentioned issue two solutions were suggested, either run all asynchronous code after super.dispose() (which IMO is not ideal since that could confuse new users about not always running it in the end) or use Future.microTask to run the asynchronous code.

Activity

  1. added
    in triage
    framework
    d: api docs
    a: error message
    team-framework
    and removed
    in triage
    on May 9, 2024
  2. added
    P3
    triaged-framework
    on May 14, 2024
  3. github-actions commented on Nov 28, 2026

    @github-actions

    This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug, including the output of flutter doctor -v and a minimal reproduction of the issue.

  4. locked as resolved and limited conversation to collaborators on Nov 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3a: error messaged: api docsframeworkteam-frameworktriaged-framework

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions