How to route from one screen to another ?
# compose
l
How to route from one screen to another ?
n
AFAIK, there’s nothing specific for compose yet. But you can use regular navigation mechanisms (activities and fragments)
l
Thank you,but I need just one single Activity
s
There's a Compose Navigation library, but it's still only available in snapshot releases. There are third party options like: https://github.com/zsoltk/compose-router
l
I know this, but it’s not perfect.
🆗 1
🤣 1
a
I've been using the NavigationViewModel from jet news sample. Seems to be okay, not the best but it works with a few modifications.
l
thank you
b
Mine does not restore after process death; that is a nice trick I'd like to work in from that NavigationViewModel
v
@Brian Beale To avoid the error “@Composable invocations can only happen from the context of a @Composable function”, replace code as following:
Copy code
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val backStack = BackStack()
        onBackPressedDispatcher.addCallback(this, backStack.callback)

        val buttonPressed = mutableStateOf(false)

        setContent {
            MaterialTheme {
                // A surface container using the 'background' color from the theme
                Surface(color = MaterialTheme.colors.background) {
                    Providers(AmbientBackStack provides backStack) {
                        NavHost(AmbientBackStack.current) {
                            println("NavHost")
                            Button(onClick = {
                                buttonPressed.value = true
                                println("1. Button pressed ${buttonPressed.value} ")
                            }) {
                                Text("Navigate forward")
                            }
                            if (buttonPressed.value) {
                                Push(true)
                                buttonPressed.value = false
                                println("2. Button pressed ${buttonPressed.value}")

                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun Push(yes : Boolean){
    if (yes) {
        AmbientBackStack.current.push {
            Text("Use the back button to go back")
        }
    }
}
b
Thanks for catching that error; I made a mistake copying things over. The @Composable invocation error is caused by AmbientBackStack.current, so if you assign that to a variable and then use that variable in the callback instead, the error should be resolved without the extra boolean state.
v
Thanks for pointing to this way.