Skip to content

Flutter does not call detachFromEngine when the shell is reset as part of applicationWillTerminate #126671

Open

Description

@fuzzybinary

Is there an existing issue for this?

Steps to reproduce

  1. Create an iOS plugin that sends messages back to Flutter on a method channel.
  2. Send messages to the method channel frequently from a separate thread on the application.
  3. Register your plugin with the registrar using -[FlutterPluginRegistrar publish:] and implementing -[FlutterPlugin detachFromEngineForRegistrar:] to stop the message send.
  4. Shutdown the app.

Expected results

Flutter calls -[FlutterPlugin detachFromEngineForRegistrar] and the app does not crash.

Actual results

In cerain situations, the app will crash with an assertion: "Sending a message before the FlutterEngine has been run." which comes from this line: https://github.com/flutter/engine/blob/8a95a0ea2699aab2d46cbd76fe8fbed551abb844/shell/platform/darwin/ios/framework/Source/FlutterEngine.mm#L1192

Code sample

Code sample
[Paste your code here]

Screenshots or Video

Screenshots / Video demonstration

[Upload media here]

Logs

Logs
[Paste your logs here]

Flutter Doctor output

Doctor output
Doctor summary (to see all details, run flutter doctor -v):
[!] Flutter (Channel stable, 3.7.6, on macOS 13.3.1 22E772610a darwin-arm64, locale en-US)
    ! Warning: `dart` on your path resolves to /opt/homebrew/Cellar/dart/2.18.7/libexec/bin/dart, which is not inside your current Flutter SDK checkout at /Users/jeff.ward/Projects/flutter.
      Consider adding /Users/jeff.ward/Projects/flutter/bin to the front of your path.
[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
[✓] Xcode - develop for iOS and macOS (Xcode 14.3)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2022.1)
[✓] VS Code (version 1.78.1)
[✓] Connected device (6 available)
[✓] HTTP Host Availability

! Doctor found issues in 1 category.

Activity

  1. fuzzybinary commented on May 12, 2023

    @fuzzybinary
    ContributorAuthor

    Very tough to provide a code sample here, but I'll come back to it and provide a github repo if I can.

    Some more information - we're suffering from this crash in the Datadog plugin, see DataDog/dd-sdk-flutter#341 (this was closed but the issue persists in newer versions). I've tracked this down to the following code path:

    1. iOS sends an ApplicationWillTerminate notification
    2. -[FlutterViewController applicationWillTerminate:] is called followed by
    3. -[FlutterEngine destroyContext] which shuts down the platform channel via _shell.reset()

    I feel like destroyContext should either:

    1. Detach plugins from the engine, similar to this codepath in -[FlutterEngine dalloc] (https://github.com/flutter/engine/blob/8a95a0ea2699aab2d46cbd76fe8fbed551abb844/shell/platform/darwin/ios/framework/Source/FlutterEngine.mm#L256)
    2. Have a separate notification for plugins to inform them that the shell is being reset
  2. added
    in triage
    on May 15, 2023
  3. darshankawar commented on May 15, 2023

    @darshankawar
    Member

    Thanks for the detailed report @fuzzybinary
    Would also be good to provide us a demo repo or a code sample that we can use to verify this behavior further.

  4. added
    waiting for response
    on May 15, 2023
  5. fuzzybinary commented on May 15, 2023

    @fuzzybinary
    ContributorAuthor
  6. removed
    waiting for response
    on May 15, 2023
  7. stuartmorgan-g commented on May 15, 2023

    @stuartmorgan-g
    Contributor

    4. Shutdown the app.

    Meaning swiping it away in the app switcher UI, I assume (given the stack)?

  8. fuzzybinary commented on May 15, 2023

    @fuzzybinary
    ContributorAuthor

    Yes. Be forewarned that taking too much time debugging when quitting like this will terminate the debug session without going through all the shutdown code (like the FlutterEngine dealloc) which makes this incredibly hard to debug.

  9. added
    c: crash
    platform-ios
    engine
    P2
    and removed
    in triage
    on May 15, 2023
  10. stuartmorgan-g commented on May 15, 2023

    @stuartmorgan-g
    Contributor

    In my opinion, this should not crash on a force quit.

    It definitely shouldn't crash.

    That said, from a prioritization standpoint this is a pretty minor issue; flows that call applicationWillTerminate on iOS are quite rare in real-world usage (most iOS users don't even know you can do that), and the effect isn't visible to non-developer users because the process going away was the expected outcome.

    (If we eventually combine more iOS and macOS engine codepaths, this would be much more important.)

  11. fuzzybinary commented on May 15, 2023

    @fuzzybinary
    ContributorAuthor

    Not going to disagree, but unfortunately it does show up in crash trackers and gets reported back to library maintainers 🙂. I think that possibly (though I can't be sure) memory pressure can also cause this exit code path. Again, deosn't affect users but does get reported to crash trackers.

    Given direction I could potentially take this on. I feel like the correct answer is to move this code path (https://github.com/flutter/engine/blob/8a95a0ea2699aab2d46cbd76fe8fbed551abb844/shell/platform/darwin/ios/framework/Source/FlutterEngine.mm#L256) into -[FlutterEngine destroyContext], but don't want to spend too much time on it if that's not the right answer.

  12. stuartmorgan-g commented on May 15, 2023

    @stuartmorgan-g
    Contributor

    I think that possibly (though I can't be sure) memory pressure can also cause this exit code path.

    It would be extremely surprising if, in the face of memory pressure, iOS chose to activate background applications in order to let them run arbitrary code, rather than just terminate them silently in the background as applications are always supposed to be designed to assume can happen.

    In many years of iOS development prior to Flutter, the only way I ever remember seeing this codepath was via the user manually swiping away the currently active application from the switcher.

  13. fuzzybinary commented on May 15, 2023

    @fuzzybinary
    ContributorAuthor

    Yes, I think you're right, that makes sense. The only way I've seen this codepath trigger is through swiping away in the application in the switcher. Though, I have seen it trigger from the inactive application in the switcher.

  14. added
    team-ios
    triaged-ios
    on Jul 8, 2023
  15. percula commented on Aug 28, 2026

    @percula

    Since migrating to FlutterSceneDelegate (3.41.2) this became my app's top production crash (~97 events/80 users a week). It didn't exist in the release before the migration.

    The problem is that sceneWillDisconnect: now calls appOrSceneWillTerminate → [engine destroyContext], and iOS disconnects backgrounded scenes routinely (in my crash reports, 6-51 minutes after backgrounding). So the shell gets destroyed regularly, plugins never get detachFromEngineForRegistrar:, and the next native callback into a stale eventSink hits the NSAssert in sendOnChannel:. For me that's mostly connectivity_plus's NWPathMonitor, with smaller buckets from cloud_firestore and firebase_auth stream handlers. The plugins do implement detach correctly, it just never runs on this path.

    I worked around the connectivity case by cancelling my subscription on AppLifecycleState.paused, but that doesn't help with streams plugins own internally (Firestore snapshot listeners etc.), and the detached message is sent synchronously right before the shell is destroyed so Dart can't clean up at teardown time.

    Could destroyContext call detachFromEngineForRegistrar: before resetting the shell? Happy to share full stacks or test a patch.

  16. Wackymax commented on Sep 8, 2026

    @Wackymax

    Hi, I managed to reproduce this with a small Flutter app without Firebase or any third-party plugins. I've put the code, steps and logs in a gist.

    The app starts a second engine and subscribes to an event channel. The native plugin is published and implements detachFromEngine(for:). If I call destroyContext() but keep the engine reference in the AppDelegate, the detach callback never runs. Calling the saved event sink 100 ms later on the main queue then crashes with:

    NSInternalInconsistencyException: Sending a message before the FlutterEngine has been run.
    

    If I release the engine reference after destroyContext(), the detach callback does run, clears the sink, and the app stays running. The plugin itself stays alive for the delayed callback in both cases.

    I tested this with Flutter 3.47.2 stable, Dart 3.13.2, Xcode 27 and an iOS 26.5 simulator. This reproduces the engine reset case directly; I haven't reproduced the full scene-disconnection or application-termination flow with this example.

    I came across this while working on firebase/flutterfire#18658. Cleaning up the Storage listener helps when the detach callback runs, but it can't handle this case if the engine doesn't notify the plugin before resetting.

  17. kmartins commented on Oct 22, 2026

    @kmartins

    Same here on Flutter 3.47.7 after migrating to FlutterSceneDelegate. Reproducible every time by swiping the app away from the app switcher.

  18. Jethro87 commented on Nov 20, 2026

    @Jethro87

    We're hitting the event-channel version of this on iOS, through connectivity_plus. I went through the engine source to see why. It looks like the same teardown problem as #195495, just on the send side.

    What I think is going on:

    1. FlutterViewController sends detached and calls destroyContext straight away (FlutterViewController.mm, line 1049). Nothing waits for Dart.
    2. destroyContext resets the shell but doesn't detach plugins. That only happens in dealloc (FlutterEngine.mm, line 573).
    3. A plugin's event sink still holds the messenger. If it fires after that, sendOnChannel: hits the _shell && _shell->IsSetup() assert (FlutterEngine.mm, line 1333).

    connectivity_plus does DispatchQueue.main.async { self.eventSink?(...) }, so a network update queued just before teardown gets sent just after it. fluttercommunity/plus_plugins#3957 fixes the dealloc case but not this one. Plugins can't really guard against it either, since nothing is guaranteed to run before destroyContext.

    A possible fix: once destroyContext has run, make sends (and handler registration, per the other issue) a logged no-op. The relay already logs "Communicating on a dead channel." when it has no parent. A test in FlutterEngineTest.mm could keep a sink, call destroyContext, then fire the sink. Today that should assert.

  19. cbracken commented on Nov 24, 2026

    @cbracken
    Member

    As a quick heads up #197310 will fix the crash but won't call detachFromEngineForRegistrar: from destroyContext. I think it's worth considering that as a followup since it's a change in behaviour.

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

    P2c: crashengineplatform-iosteam-iostriaged-ios

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions