Any proper way of handling backpress in compose mu...
# compose
s
Any proper way of handling backpress in compose multiplatform?
t
I'm thinking you'll need an expect/actual to handle this. You'll should just need to override the OnBackPressed for Android and dismiss() for iOS. I'm not sure if there's a library yet for this functionality, but it would probably be nice to have if there isn't.
s
read about BackHandler class in CMP but it's not working lol
t
I unfortunately haven’t had a use case for it so I was only going by some quick research. This is some code from chat GPT: // androidMain private var backCallback: OnBackPressedCallback? = null actual fun registerBackHandler(onBack: () -> Unit) { val activity = currentActivity ?: return backCallback = object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { onBack() } } activity.onBackPressedDispatcher.addCallback(backCallback!!) } actual fun unregisterBackHandler() { backCallback?.remove() backCallback = null } // Helper to get current activity (can vary depending on your setup) val currentActivity: ComponentActivity? get() = /* your Activity reference retrieval logic */ So you have the setup for some expect/actuals. The ios side will need a tie into gestures and pops. Alternatively to all this, the navigation library Decompose has a built in onBackPressed method that you can use for its behavior in the simplest way possible. I use Decompose and love it as it’s very feature rich and has a lot of common uses solutioned.
m
I think the main thing here to remember is that a "back button" is not universal. Sure it exists on android as soft button or a gesture, and it exists on iOS as a gesture as well. But what about desktop? There's really no concept of a "back" in desktop. As such i think an expect actual as people have suggested above is your best bet, and to the right thing for each platform you support.
a
On desktop we have the Esc button, or whatever you want to use as back. Should be easy to bind with Decompose, not sure about other libs.
v
If you add:
Copy code
implementation("org.jetbrains.compose.ui:ui-backhandler:1.8.0-alpha03")
BackHandler + PredictiveBackHandler will become present in the
commonMain
source
s
@Vidmantas Kerbelis tried that but didn;t work at all on iOS, not sure if we need to integrate in a different way for both platforms.. i just added backhandler(predictive =true) { navcomtroller.pop() } in the root compose