I want to intercept the back gesture or tap (e.g., swiping back on iOS or pressing the back button or gesture on Android) to show a dialog before exiting a screen.
I understand that in Jetpack Compose, I could use BackHandler, but since I am working with Compose Multiplatform, that is not an option. It seems I might need to implement platform-specific logic to achieve this.
I’ve searched for solutions or examples related to this issue but haven’t found any information specifically for Compose Multiplatform. How can I handle this behavior for both Android and iOS? Thanks
For any future readers, Compose Multiplatform has officially implemented BackHandler and PredictiveBackHandler in compose multiplatform version 1.8.0-alpha03.
In order to use that, first add this dependency in your build-gradle commonMain:
implementation("org.jetbrains.compose.ui:ui-backhandler")
After that you can use BackHandler in your compose common-main code:
androidx.compose.ui.backhandler.BackHandler(true) {
//your back pressed logic here
}
⚠️ Update (Compose Multiplatform 1.9.1)
If you've upgraded to compose-plugin = "1.9.1", you now need to explicitly specify the version for the BackHandler dependency.
Otherwise, you may encounter an "unresolved dependency" error in your build.gradle file.
implementation("org.jetbrains.compose.ui:ui-backhandler:1.9.1")
✅ Update (Compose Multiplatform 1.10.0+)
As of Compose 1.10.0, the BackHandler from ui-backhandler has been deprecated in favor of NavigationBackHandler.
To use the new API, add this dependency to your version catalog:
composeNavigationEvent = "1.0.0"
And in your dependencies:
compose-navigationevent = { module = "org.jetbrains.androidx.navigationevent:navigationevent-compose", version.ref = "composeNavigationEvent" }
Then use NavigationBackHandler in your code instead of the deprecated BackHandler:
NavigationBackHandler(
state = rememberNavigationEventState(NavigationEventInfo.None),
isBackEnabled = true, // You can toggle this dynamically
onBackCompleted = {
//back pressed logic here
}
)
Since 1.8.0-alpha03, there is a solution on Compose Multiplatform itself! https://github.com/JetBrains/compose-multiplatform/releases/tag/v1.8.0-alpha03
There is a small weird thing: You can't access BackHandler and PredictiveBackHandler on your code unless you manually implement the following library: org.jetbrains.compose.ui:ui-backhandler
After that it should work, at least for this alpha version it is the only solution
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With