Dung (Donny) Nguyen

Senior Software Engineer

Bad State: Future Already Completed

The Dart error Bad state: Future already completed occurs when you attempt to complete a Future more than once. Since a Future in Dart can only transition from an uncompleted state to a completed state exactly once, any subsequent attempt to complete it will throw this error.

Here are the most common reasons for this error:

1. Manually Completing a Completer Multiple Times

2. Multiple Calls to an async Function or Callback

3. Stream Subscription and Repeated Calls

4. Rethrowing or Propagating Errors

5. Race Conditions

6. Incorrect Logic in Custom Future-Based APIs


How to Fix the Issue

  1. Check Completion State Before Completing: Use the Completer.isCompleted property to verify if the Completer is already completed.
    if (!completer.isCompleted) {
      completer.complete();
    }
    
  2. Guard Against Multiple Calls: Ensure that Future completion logic is invoked only once. For example, debounce or synchronize access to shared resources.

  3. Refactor Code for Better Design: Avoid scenarios where multiple parts of the code compete to complete the same Future.

  4. Use Debugging Tools: Add logging or breakpoints to track where the Future is being completed to identify duplicate completions.