Fixes crashes on Android when rememberFilePickerLauncher() is called inside androidx.compose.ui.window.Dialog
When dialog is created Context is wrapped in ContextThemeWrapper and when attempt is made to cast it to ComponentActivity it crashes with java.lang.ClassCastException
Use LocalActivityResultRegistryOwner as a fix.
It either stores a composition local instance of ActivityResultRegistryOwner or unwraps compositon local context until it finds activity that implements ActivityResultRegistryOwner (most oftent it is ComponentActivity)
Example to reproduce the crash:
@Composable
fun App() {
MaterialTheme {
var showDialog by remember { mutableStateOf(false) }
Button(onClick = { showDialog = true }) {
Text("Show dialog")
}
if (showDialog) {
Dialog(onDismissRequest = { showDialog = false }) {
var files: Set<PlatformFile> by remember { mutableStateOf(emptySet()) }
val singleFilePicker = rememberFilePickerLauncher(
type = PickerType.Image,
title = "Single file picker",
onResult = { file -> file?.let { files += it } }
)
Button(onClick = { singleFilePicker.launch() }) {
Text("Single file picker")
}
}
}
}
}
Fixes crashes on Android when rememberFilePickerLauncher() is called inside
androidx.compose.ui.window.Dialog
When dialog is created Context is wrapped in
ContextThemeWrapper
and when attempt is made to cast it toComponentActivity
it crashes withjava.lang.ClassCastException
Use
LocalActivityResultRegistryOwner
as a fix. It either stores a composition local instance ofActivityResultRegistryOwner
or unwraps compositon local context until it finds activity that implementsActivityResultRegistryOwner
(most oftent it isComponentActivity
)Example to reproduce the crash: