Instantly share code, notes, and snippets.
Created
June 5, 2022 11:06
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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