mvarnagiris / compose-navigation

Apache License 2.0
65 stars 4 forks source link

compose-navigation

Download

Add Jitpack repository to your top level build.gradle:

allprojects {
    repositories {
        maven { url 'https://jitpack.io' }
    }
}

Add dependency in your app build.gradle:

implementation 'com.github.mvarnagiris.compose-navigation:navigation:{latest_version}'

How to use

Define your navigation routes. Best way to do that is to use a sealed class. Each route can contain all necessary parameters for your screens.

sealed class AppRoute {
    object SplashRoute : AppRoute()
    object HomeRoute : AppRoute()
    data class DetailsRoute(val id: String) : AppRoute()
}

Wherever you want routing to happen add Router:

@Composable
fun AppRoot() {
    Router<AppRoute>(start = SplashRoute) { currentRoute ->
        // this lambda has this signature: BackStack<AppRoute>.(Route<AppRoute>) -> Unit
        // this is BackStack<AppRoute>. So you can call BackStack methods easily like push(...), pop(), etc.
        // currentRoute is Route<AppRoute> that contains current AppRoute as data and other metadata like back stack identifier
        when (val route = currentRoute.data) {
            SplashRoute -> SplashScreen(onInitialized = { replace(HomeRoute) })
            HomeRoute -> HomeScreen(onDetailsSelected = { id -> push(DetailsRoute(id)) })
            is DetailsRoute -> DetailsScreen(route.id)
        }
    }
}

@Composable
fun SplashScreen(onInitialized: () -> Unit) {
    // ...
}

@Composable
fun HomeScreen(onDetailsSelected: (String) -> Unit) {
    // ...
}

@Composable
fun DetailsScreen(id: String) {
    // ...
}

BackStack operations:

backStackController.pop() will pop from global back stack. Each Router has it's own BackStack and all of them are controlled by backStackController which has global back stack.

For more examples check out the sample app