adrielcafe / voyager

🛸 A pragmatic navigation library for Jetpack Compose
https://voyager.adriel.cafe
MIT License
2.61k stars 142 forks source link

Pass data to previous composable screens #465

Open GvHarish9894 opened 4 months ago

GvHarish9894 commented 4 months ago

Feature need to pass data to previous composable screens like traditional android navigation library previousBackStackEntry kind of function

newstrong commented 1 month ago

It's necessary.

Khudoyshukur commented 4 days ago

I did a custom workaround for passing data between composables. One composable sets the result and another composable can fetch it by its key. After the result consumed, it is cleared from the memory.

// NavigationResult.kt
private val screenResults = hashMapOf<String, Any?>()

fun <T: Any> Navigator.getScreenResult(key: String): T? {
    val result = screenResults[key]
    screenResults[key] = null

    return result as? T
}

fun Navigator.setScreenResult(key: String, result: Any) {
    screenResults[key] = result
}
class ScreenA : Screen {

    @Composable
    override fun Content() {
        val navigator = LocalNavigator.current

        LaunchedEffect(Unit) {
            val screenResult = navigator?.getScreenResult<String>("MY_RESULT")
            println("Screen result is $screenResult")
        }

        Text(
            modifier = Modifier.clickable { navigator?.push(ScreenB()) },
            text = "ClickMe"
        )
    }
}

class ScreenB : Screen {

    @Composable
    override fun Content() {
        val navigator = LocalNavigator.current

        BackHandler(
            enabled = true,
            onBack = {
                navigator?.setScreenResult("MY_RESULT", "RESULT")
                navigator?.pop()
            }
        )
    }
}