Flutter deactivate setstate during build

From divinevideo/divine-mobile · View interactive version

Flutter deactivate setstate during build is an AI agent skill from the GitHub repository divinevideo/divine-mobile. Fix "setState() or markNeedsBuild() called during build" error triggered from deactivate(). Use when: (1) Error occurs during widget disposal or navigation away, (2) Stack trace shows deactivate -> some notifier -> ValueListenableBuilder._valueChanged, (3) Video/audio player pause() or stop() calls

How to use this skill

Skill file

Flutter: setState During Build from deactivate()

Problem

When navigating away from a screen, calling methods like VideoPlayerController.pause() in

deactivate() triggers setState() or markNeedsBuild() called during build because the

controller notifies its listeners synchronously during widget tree teardown.

Context / Trigger Conditions

Solution

Defer the state-modifying operation to after the current frame:

@override
void deactivate() {
  // Capture controller reference while ref/context is still valid
  final controller = _getController();

  // Defer pause to after current frame
  if (controller != null && controller.value.isPlaying) {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (controller.value.isPlaying) {
        controller.pause();
      }
    });
  }

  super.deactivate();
}

Key Insights

  1. Why deactivate() is problematic: It's called during the widget tree teardown phase,

which is part of the build process. Any synchronous notification to listeners will

trigger rebuilds during build.

  1. Why dispose() doesn't have this issue: By dispose(), the widget is fully unmounted

and listeners are typically already removed.

  1. Capture references early: Get controller/state references before the async gap

since ref, context, or other widget state may become invalid.

  1. Guard against double-execution: Check isPlaying again in the callback since

state may have changed.

Verification

Example: Full Implementation

class _FullscreenVideoScreenState extends ConsumerState<FullscreenVideoScreen> {
  @override
  void deactivate() {
    _schedulePauseCurrentVideo();
    super.deactivate();
  }

  void _schedulePauseCurrentVideo() {
    final controller = _getCurrentController();
    if (controller == null || !controller.value.isInitialized) {
      return;
    }

    // Defer to avoid setState during build
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (controller.value.isPlaying) {
        controller.pause();
      }
    });
  }
}

Notes

controller.pause() without notifying, though this breaks the observer pattern

Related Patterns

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.