You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Flutter does not call detachFromEngine when the shell is reset as part of applicationWillTerminate #126671
P2Important issues not at the top of the work listc: crashStack traces logged to the consoleengineflutter/engine related. See also e: labels.platform-iosiOS applications specificallyteam-iosOwned by iOS platform teamtriaged-iosTriaged by iOS platform team
Create an iOS plugin that sends messages back to Flutter on a method channel.
Send messages to the method channel frequently from a separate thread on the application.
Register your plugin with the registrar using -[FlutterPluginRegistrar publish:] and implementing -[FlutterPlugin detachFromEngineForRegistrar:] to stop the message send.
Shutdown the app.
Expected results
Flutter calls -[FlutterPlugin detachFromEngineForRegistrar] and the app does not crash.
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.
Reacted by KoI, Rodrigo Pequeno, Adeyemo Adedamola, Muhammad Alif Akbar, Hugo Delaunay, flutter-kim-json, JP and Kauê Martins
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:
iOS sends an ApplicationWillTerminate notification
-[FlutterViewController applicationWillTerminate:] is called followed by
-[FlutterEngine destroyContext] which shuts down the platform channel via _shell.reset()
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.
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.
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.)
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.
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.
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.
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.
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.
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:
FlutterViewController sends detached and calls destroyContext straight away (FlutterViewController.mm, line 1049). Nothing waits for Dart.
destroyContext resets the shell but doesn't detach plugins. That only happens in dealloc (FlutterEngine.mm, line 573).
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.
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.
P2Important issues not at the top of the work listc: crashStack traces logged to the consoleengineflutter/engine related. See also e: labels.platform-iosiOS applications specificallyteam-iosOwned by iOS platform teamtriaged-iosTriaged by iOS platform team
Activity
fuzzybinary commentedon May 12, 2023
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:
ApplicationWillTerminatenotification-[FlutterViewController applicationWillTerminate:]is called followed by-[FlutterEngine destroyContext]which shuts down the platform channel via_shell.reset()I feel like
destroyContextshould either:-[FlutterEngine dalloc](https://github.com/flutter/engine/blob/8a95a0ea2699aab2d46cbd76fe8fbed551abb844/shell/platform/darwin/ios/framework/Source/FlutterEngine.mm#L256)darshankawar commentedon May 15, 2023
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.
fuzzybinary commentedon May 15, 2023
Hi @darshankawar,
Here's my example: https://github.com/fuzzybinary/flutter_shutdown_crash
In my opinion, this should not crash on a force quit.
stuartmorgan-g commentedon May 15, 2023
Meaning swiping it away in the app switcher UI, I assume (given the stack)?
fuzzybinary commentedon May 15, 2023
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.
stuartmorgan-g commentedon May 15, 2023
It definitely shouldn't crash.
That said, from a prioritization standpoint this is a pretty minor issue; flows that call
applicationWillTerminateon 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.)
fuzzybinary commentedon May 15, 2023
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.stuartmorgan-g commentedon May 15, 2023
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.
fuzzybinary commentedon May 15, 2023
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.
percula commentedon Aug 28, 2026
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 callsappOrSceneWillTerminate→[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 getdetachFromEngineForRegistrar:, and the next native callback into a staleeventSinkhits theNSAssertinsendOnChannel:. For me that's mostly connectivity_plus'sNWPathMonitor, 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 thedetachedmessage is sent synchronously right before the shell is destroyed so Dart can't clean up at teardown time.Could
destroyContextcalldetachFromEngineForRegistrar:before resetting the shell? Happy to share full stacks or test a patch.Wackymax commentedon Sep 8, 2026
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 calldestroyContext()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: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.
fix(ios): detach plugin when Flutter tears down an engine that stays …
kmartins commentedon Oct 22, 2026
Same here on Flutter 3.47.7 after migrating to
FlutterSceneDelegate. Reproducible every time by swiping the app away from the app switcher.Jethro87 commentedon Nov 20, 2026
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:
FlutterViewControllersendsdetachedand callsdestroyContextstraight away (FlutterViewController.mm, line 1049). Nothing waits for Dart.destroyContextresets the shell but doesn't detach plugins. That only happens indealloc(FlutterEngine.mm, line 573).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 beforedestroyContext.A possible fix: once
destroyContexthas 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, calldestroyContext, then fire the sink. Today that should assert.cbracken commentedon Nov 24, 2026
As a quick heads up #197310 will fix the crash but won't call
detachFromEngineForRegistrar:fromdestroyContext. I think it's worth considering that as a followup since it's a change in behaviour.iOS: Ignore platform messages after the engine is destroyed (flutter#…