Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// 1. Initialize Navigator in Activity or Fragment
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
...
val navigator = ComposeNavigator.with(this, savedInstanceState).initialize()
setContent {
...
MainScreen(navigator) // <-- Line: 34
}
}
}
// 2. Define Routes (destination)
sealed class MainRoute : Route {
@Immutable @Parcelize
data class First(val data: String) : MainRoute()
@Immutable @Parcelize
data class Second(private val noArg: String = "") : MainRoute() // no arg route
companion object Key : Route.Key<MainRoute> // <-- Unique key for the root
}
@Composable // associated with MainRoute.First
fun FirstScreen(data: String, changed: (screen: Route) -> Unit) {...}
@Composable // associated with MainRoute.Second
fun SecondScreen() {...}
// 3. Setup Navigation
@Composable
fun MainScreen(navigator: ComposeNavigator) {
// remember instance of controller, this will help you to manage navigation
// for type MainRoute
val controller = rememberNavController<MainRoute>()
navigator.Setup(key = MainRoute.key, initial = MainRoute.First("Hello world"), controller = controller) { dest ->
val goToSecond: () -> Unit = { value ->
controller.navigateTo(MainRoute.Second()) // <-- Navigate to Second Route
}
when (dest) {
is MainRoute.First -> FirstScreen(dest.data, goToSecond)
is MainRoute.Second -> SecondScreen()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment