Skip to content

OverlayPortal: Failed to attach OverlayPortalController to _OverlayPortalState on page resize #164376

Closed

Description

@berrywhite96

Steps to reproduce

Just use two OverlayPortals which are new builded by parent widget, e.g. on resize like the Switchy widget does.
Tested it with web on Flutter 3.29.0 and 3.22.3, same result.

Expected results

Controller is not attached anymore to old state so on rebuild it can be used again.

Actual results

Exception on rebuild.

Code sample

Code sample
class MainApp extends StatefulWidget {
  const MainApp({super.key});

  @override
  State<MainApp> createState() => _MainAppState();
}

class _MainAppState extends State<MainApp> {
  final OverlayPortalController overlayPortalController = OverlayPortalController();

  final OverlayPortalController overlayPortalControllerSecond = OverlayPortalController();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SingleChildScrollView(
        child: Switchy(
          children: [
            PortaledWidget(controller: overlayPortalController),
            PortaledWidget(controller: overlayPortalControllerSecond),
          ],
        ),
      ),
    );
  }
}

class Switchy extends StatelessWidget {
  final List<Widget> children;

  const Switchy({super.key, required this.children});

  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.sizeOf(context);

    if (size.width < 800) {
      return Column(children: children);
    }
    return Row(children: children);
  }
}

class PortaledWidget extends StatelessWidget {
  final OverlayPortalController controller;

  const PortaledWidget({super.key, required this.controller});

  @override
  Widget build(BuildContext context) {
    return OverlayPortal(
      controller: controller,
      overlayChildBuilder: (context) => ElevatedButton(
        onPressed: () => controller.hide(),
        child: const Text('cancel'),
      ),
      child: ElevatedButton.icon(onPressed: () => controller.show(), label: const Icon(Icons.home)),
    );
  }
}

Screenshots or Video

Screenshots / Video demonstration
Bildschirmaufnahme.2025-02-28.um.12.57.09.mov

Logs

Logs
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following assertion was thrown building PortaledWidget:
Assertion failed:
file:///Users/bs000ucwu/flutter/3.29.0/packages/flutter/lib/src/widgets/overlay.dart:1881:7
overlay.dart:1881
controller._attachTarget == null || controller._attachTarget == this
"Failed to attach OverlayPortalController to _OverlayPortalState#73413(lifecycle state: created). It
is already attached to _OverlayPortalState#d6d85."

The relevant error-causing widget was:
  PortaledWidget PortaledWidget:file:///Users/bs000ucwu/flutter_test_project/lib/main.dart:25:13

When the exception was thrown, this was the stack:
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 307:3     throw_
errors.dart:307
dart-sdk/lib/_internal/js_dev_runtime/private/profile.dart 117:39               assertFailed
profile.dart:117
packages/flutter/src/widgets/overlay.dart 1881:71                               [_setupController]
overlay.dart:1881
packages/flutter/src/widgets/overlay.dart 1876:5                                initState
overlay.dart:1876
packages/flutter/src/widgets/framework.dart 5860:55                             [_firstBuild]
framework.dart:5860
packages/flutter/src/widgets/framework.dart 5709:5                              mount
framework.dart:5709
packages/flutter/src/widgets/framework.dart 4555:15                             inflateWidget
framework.dart:4555
packages/flutter/src/widgets/framework.dart 4020:18                             updateChild
framework.dart:4020
packages/flutter/src/widgets/framework.dart 5756:16                             performRebuild
framework.dart:5756
packages/flutter/src/widgets/framework.dart 5445:7                              rebuild
framework.dart:5445
packages/flutter/src/widgets/framework.dart 5715:5                              [_firstBuild]
framework.dart:5715
packages/flutter/src/widgets/framework.dart 5709:5                              mount
framework.dart:5709
packages/flutter/src/widgets/framework.dart 4555:15                             inflateWidget
framework.dart:4555
packages/flutter/src/widgets/framework.dart 7178:36                             inflateWidget
framework.dart:7178
packages/flutter/src/widgets/framework.dart 7194:32                             mount
framework.dart:7194
packages/flutter/src/widgets/framework.dart 4555:15                             inflateWidget
framework.dart:4555
packages/flutter/src/widgets/framework.dart 4014:20                             updateChild
framework.dart:4014
packages/flutter/src/widgets/framework.dart 5756:16                             performRebuild
framework.dart:5756
packages/flutter/src/widgets/framework.dart 5445:7                              rebuild
framework.dart:5445
packages/flutter/src/widgets/framework.dart 2704:14                             [_tryRebuild]
framework.dart:2704
packages/flutter/src/widgets/framework.dart 2762:11                             [_flushDirtyElements]
framework.dart:2762
packages/flutter/src/widgets/framework.dart 3066:17                             buildScope
framework.dart:3066
packages/flutter/src/widgets/binding.dart 1229:9                                drawFrame
binding.dart:1229
packages/flutter/src/rendering/binding.dart 482:5                               [_handlePersistentFrameCallback]
binding.dart:482
packages/flutter/src/scheduler/binding.dart 1442:7                              [_invokeFrameCallback]
binding.dart:1442
packages/flutter/src/scheduler/binding.dart 1355:9                              handleDrawFrame
binding.dart:1355
packages/flutter/src/scheduler/binding.dart 1208:5                              [_handleDrawFrame]
binding.dart:1208
lib/_engine/engine/platform_dispatcher.dart 1347:5                              invoke
platform_dispatcher.dart:1347
lib/_engine/engine/platform_dispatcher.dart 301:5                               invokeOnDrawFrame
platform_dispatcher.dart:301
lib/_engine/engine/initialization.dart 190:36                                   <fn>
initialization.dart:190
dart-sdk/lib/_internal/js_dev_runtime/patch/js_allow_interop_patch.dart 224:27  _callDartFunctionFast1
js_allow_interop_patch.dart:224

════════════════════════════════════════════════════════════════════════════════════════════════════
9
Another exception was thrown: Assertion failed: file:///Users/bs000ucwu/flutter/3.29.0/packages/flutter/lib/src/widgets/overlay.dart:1881:7

Flutter Doctor output

Doctor output
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.29.0, on macOS 15.3.1 24D70 darwin-arm64, locale de-DE)
[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
[✓] Xcode - develop for iOS and macOS (Xcode 16.2)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2024.2)
[✓] VS Code (version 1.97.2)
[✓] Connected device (3 available)
[✓] Network resources

• No issues found!

Activity

  1. xaldarof commented on Feb 28, 2025

    @xaldarof
  2. berrywhite96 commented on Feb 28, 2025

    @berrywhite96
    Author

    Hi, can you try this?

    https://gist.github.com/xaldarof/36c072ba56547d201517203fe80f9f8a

    This works, but I want the controller in the parent widget.

  3. maheshj01 commented on Feb 28, 2025

    @maheshj01
    Member

    Reproducible on latest stable and the master channel.

    logs
    (.venv) mahesh@MacBook-Pro-9 sample_app % flutterm run -d macos
    
    ┌─────────────────────────────────────────────────────────┐
    │ A new version of Flutter is available!                  │
    │                                                         │
    │ To update to the latest version, run "flutter upgrade". │
    └─────────────────────────────────────────────────────────┘
    Resolving dependencies... 
    Downloading packages... 
    > async 2.13.0 (was 2.12.0)
    > fake_async 1.3.3 (was 1.3.2)
      flutter_plugin_android_lifecycle 2.0.24 (2.0.26 available)
      go_router 14.8.0 (14.8.1 available)
    > leak_tracker 10.0.9 (was 10.0.8)
      material_color_utilities 0.11.1 (0.12.0 available)
    > vm_service 15.0.0 (was 14.3.1)
    > webdriver 3.1.0 (was 3.0.4)
    Changed 5 dependencies!
    3 packages have newer versions incompatible with dependency constraints.
    Try `flutter pub outdated` for more information.
    Launching lib/main.dart on macOS in debug mode...
    Running pod install...                                           1,085ms
    --- xcodebuild: WARNING: Using the first of multiple matching destinations:
    { platform:macOS, arch:arm64, id:00008132-0009284E1E39001C, name:My Mac }
    { platform:macOS, arch:x86_64, id:00008132-0009284E1E39001C, name:My Mac }
    Building macOS application...                                           
    ✓ Built build/macos/Build/Products/Debug/sample_app.app
    2025-02-28 16:49:15.855 sample_app[52015:959180] +[IMKClient subclass]: chose IMKClient_Modern
    2025-02-28 16:49:15.855 sample_app[52015:959180] +[IMKInputSession subclass]: chose IMKInputSession_Modern
    Syncing files to device macOS...                                    77ms
    
    Flutter run key commands.
    r Hot reload. 🔥🔥🔥
    R Hot restart.
    h List all available interactive commands.
    d Detach (terminate "flutter run" but leave application running).
    c Clear the screen
    q Quit (terminate the application on the device).
    
    A Dart VM Service on macOS is available at: http://127.0.0.1:58871/dNRn4p23ams=/
    The Flutter DevTools debugger and profiler on macOS is available at:
    http://127.0.0.1:9101?uri=http://127.0.0.1:58871/dNRn4p23ams=/
    
    ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
    The following assertion was thrown building PortaledWidget:
    Failed to attach OverlayPortalController to _OverlayPortalState#d1a3f(lifecycle state: created). It
    is already attached to _OverlayPortalState#42310.
    'package:flutter/src/widgets/overlay.dart':
    Failed assertion: line 1862 pos 7: 'controller._attachTarget == null || controller._attachTarget ==
    this'
    
    Either the assertion indicates an error in the framework itself, or we should provide substantially
    more information in this error message to help you determine and fix the underlying cause.
    In either case, please report this assertion by filing a bug on GitHub:
      https://github.com/flutter/flutter/issues/new?template=2_bug.yml
    
    The relevant error-causing widget was:
      PortaledWidget PortaledWidget:file:///Users/mahesh/Development/Triage/sample_app/lib/main.dart:37:13
    
    When the exception was thrown, this was the stack:
    #2      _OverlayPortalState._setupController (package:flutter/src/widgets/overlay.dart:1862:7)
    #3      _OverlayPortalState.initState (package:flutter/src/widgets/overlay.dart:1857:5)
    #4      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:5842:55)
    #5      ComponentElement.mount (package:flutter/src/widgets/framework.dart:5691:5)
    ...     Normal element mounting (7 frames)
    #12     Element.inflateWidget (package:flutter/src/widgets/framework.dart:4539:16)
    #13     MultiChildRenderObjectElement.inflateWidget (package:flutter/src/widgets/framework.dart:7159:36)
    #14     MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:7175:32)
    #15     Element.inflateWidget (package:flutter/src/widgets/framework.dart:4539:16)
    #16     Element.updateChild (package:flutter/src/widgets/framework.dart:3998:20)
    #17     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:5738:16)
    #18     Element.rebuild (package:flutter/src/widgets/framework.dart:5427:7)
    #19     BuildScope._tryRebuild (package:flutter/src/widgets/framework.dart:2694:15)
    #20     BuildScope._flushDirtyElements (package:flutter/src/widgets/framework.dart:2752:11)
    #21     BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:3056:18)
    #22     WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:1229:21)
    #23     RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:495:5)
    #24     SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1430:15)
    #25     SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1343:9)
    #26     SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:1196:5)
    #27     _invoke (dart:ui/hooks.dart:326:13)
    #28     PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:437:5)
    #29     _drawFrame (dart:ui/hooks.dart:298:31)
    (elided 2 frames from class _AssertionError)
    
    ════════════════════════════════════════════════════════════════════════════════════════════════════
    
    Another exception was thrown: Failed to attach OverlayPortalController to _OverlayPortalState#a9850(lifecycle state:
    created). It is already attached to _OverlayPortalState#ce5f7.
    Another exception was thrown: A RenderFlex overflowed by 199191 pixels on the right.
    flutter doctor -v
    [!] Flutter (Channel stable, 3.29.0, on macOS 15.1.1 24B2091 darwin-arm64, locale en-US) [613ms]
        • Flutter version 3.29.0 on channel stable at /Users/mahesh/Development/flutter
          /Users/mahesh/Development/flutter/bin to the front of your path.
        • Upstream repository https://github.com/flutter/flutter.git
        • Framework revision 35c388afb5 (3 weeks ago), 2025-02-10 12:48:41 -0800
        • Engine revision f73bfc4522
        • Dart version 3.7.0
        • DevTools version 2.42.2
        • If those were intentional, you can disregard the above warnings; however it is recommended to use "git"
          directly to perform update checks and upgrades.
    
    [✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0) [1,762ms]
        • Android SDK at /Users/mahesh/Library/Android/sdk
        • Platform android-35, build-tools 34.0.0
        • ANDROID_HOME = /Users/mahesh/Library/Android/sdk
        • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
          This is the JDK bundled with the latest Android Studio installation on this machine.
          To manually set the JDK path, use: `flutter config --jdk-dir="path/to/jdk"`.
        • Java version OpenJDK Runtime Environment (build 17.0.11+0-17.0.11b1207.24-11852314)
        • All Android licenses accepted.
    
    [✓] Xcode - develop for iOS and macOS (Xcode 16.0) [1,092ms]
        • Xcode at /Applications/Xcode.app/Contents/Developer
        • Build 16A242d
        • CocoaPods version 1.16.2
    
    [✓] Chrome - develop for the web [131ms]
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [✓] Android Studio (version 2024.1) [130ms]
        • Android Studio at /Applications/Android Studio.app/Contents
        • Flutter plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/9212-flutter
        • Dart plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/6351-dart
        • Java version OpenJDK Runtime Environment (build 17.0.11+0-17.0.11b1207.24-11852314)
    
    [✓] IntelliJ IDEA Community Edition (version 2021.2.1) [129ms]
        • IntelliJ at /Applications/IntelliJ IDEA CE.app
        • Flutter plugin version 61.2.4
        • Dart plugin version 212.5080.8
    
    [✓] VS Code (version 1.96.2) [18ms]
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.102.0
    
    [✓] Connected device (3 available) [6.5s]
        • macOS (desktop)                 • macos                 • darwin-arm64   • macOS 15.1.1 24B2091 darwin-arm64
        • Mac Designed for iPad (desktop) • mac-designed-for-ipad • darwin         • macOS 15.1.1 24B2091 darwin-arm64
        • Chrome (web)                    • chrome                • web-javascript • Google Chrome 131.0.6778.265
    
    [✓] Network resources [293ms]
        • All expected network resources are available.
    
    ! Doctor found issues in 1 category.
    
    [✓] Flutter (Channel master, 3.30.0-1.0.pre.330, on macOS 15.1.1 24B2091 darwin-arm64, locale en-US) [2.9s]
        • Flutter version 3.30.0-1.0.pre.330 on channel master at /Users/mahesh/Development/flutter_master
        • Upstream repository https://github.com/flutter/flutter.git
        • Framework revision 99e1a0652c (3 days ago), 2025-02-25 16:59:54 -0800
        • Engine revision 99e1a0652c
        • Dart version 3.8.0 (build 3.8.0-133.0.dev)
        • DevTools version 2.43.0
    
    [✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0) [2.5s]
        • Android SDK at /Users/mahesh/Library/Android/sdk
        • Platform android-35, build-tools 34.0.0
        • ANDROID_HOME = /Users/mahesh/Library/Android/sdk
        • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
          This is the JDK bundled with the latest Android Studio installation on this machine.
          To manually set the JDK path, use: `flutter config --jdk-dir="path/to/jdk"`.
        • Java version OpenJDK Runtime Environment (build 17.0.11+0-17.0.11b1207.24-11852314)
        • All Android licenses accepted.
    
    [✓] Xcode - develop for iOS and macOS (Xcode 16.0) [1,428ms]
        • Xcode at /Applications/Xcode.app/Contents/Developer
        • Build 16A242d
        • CocoaPods version 1.16.2
    
    [✓] Chrome - develop for the web [138ms]
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [✓] Android Studio (version 2024.1) [137ms]
        • Android Studio at /Applications/Android Studio.app/Contents
        • Flutter plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/9212-flutter
        • Dart plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/6351-dart
        • Java version OpenJDK Runtime Environment (build 17.0.11+0-17.0.11b1207.24-11852314)
    
    [✓] IntelliJ IDEA Community Edition (version 2021.2.1) [135ms]
        • IntelliJ at /Applications/IntelliJ IDEA CE.app
        • Flutter plugin version 61.2.4
        • Dart plugin version 212.5080.8
    
    [✓] VS Code (version 1.96.2) [18ms]
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.102.0
    
    [✓] Connected device (2 available) [6.7s]
        • macOS (desktop) • macos  • darwin-arm64   • macOS 15.1.1 24B2091 darwin-arm64
        • Chrome (web)    • chrome • web-javascript • Google Chrome 131.0.6778.265
    
    [✓] Network resources [373ms]
        • All expected network resources are available.
    
    • No issues found!
    
  4. added
    frameworkflutter/packages/flutter repository. See also f: labels.
    has reproducible stepsThe issue has been confirmed reproducible and is ready to work on
    and removed
    in triagePresently being triaged by the triage team
    on Feb 28, 2025
  5. LongCatIsLooong commented on Mar 1, 2025

    @LongCatIsLooong
    Contributor

    IIRC the assert was added to make sure the controller can't be attached to more than one OverlayPortal.

    • The error message should be clear about what the violation is
    • It should support swapping controllers like swapping GlobalKeys

    As a workaround you could give those OverlayPortals global keys so they are reused when you resize the screen.

  6. berrywhite96 commented on Mar 3, 2025

    @berrywhite96
    Author

    IIRC the assert was added to make sure the controller can't be attached to more than one OverlayPortal.

    • The error message should be clear about what the violation is
    • It should support swapping controllers like swapping GlobalKeys

    As a workaround you could give those OverlayPortals global keys so they are reused when you resize the screen.

    This works for now. Thanks for the quick support and fix!

  7. sharabiddin commented on Mar 3, 2025

    @sharabiddin
    Contributor

    @berrywhite96 I was going to open issue too (and saw this), thanks for notifying the community about the bug

  8. added a commit that references this issue on Mar 26, 2025
    97167ed
  9. added
    r: fixedIssue is closed as already fixed in a newer version
    on Mar 26, 2025
  10. github-actions commented on Apr 9, 2025

    @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.

  11. locked as resolved and limited conversation to collaborators on Apr 9, 2025
  12. added a commit that references this issue on Jun 9, 2025
    9aadf88
  13. added a commit that references this issue on Aug 14, 2025
    8b3afb7
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

    P2Important issues not at the top of the work listc: crashStack traces logged to the consolefound in release: 3.29Found to occur in 3.29found in release: 3.30Found to occur in 3.30frameworkflutter/packages/flutter repository. See also f: labels.has reproducible stepsThe issue has been confirmed reproducible and is ready to work onr: fixedIssue is closed as already fixed in a newer versionteam-frameworkOwned by Framework teamtriaged-frameworkTriaged by Framework teamwaiting for PR to land (fixed)A fix is in flightworkaround availableThere is a workaround available to overcome the issue

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions