Skip to content

Compose Navigator Tutorials

Kaustubh Patange edited this page Jul 7, 2021 · 20 revisions

These are small tutorials that covers some specific implementation detail.

Table of contents

Navigating with arguments

When you declare a Route say a sealed class (shown in Quick setup), the constructor parameters of the individual destination becomes the argument for that destination.

// Go to Quick setup guide to see the full example.
navigator.Setup(...) { controller, dest ->
    when(dest) {
        is MainRoute.First -> FirstScreen(dest.data, onChanged)
    }
}

Kotlin's is keyword will smartly cast the dest to the type we have specified so that we can easily access the arguments.

Navigating with animation

Navigator allows you to set transitions for target and current destination.

Each transition extends from com.kpstv.navigation.compose.NavigatorTransition interface which contains two important properties forwardTransition & backwardTransition (which you have to implement) that returns Modifier object.

Suppose A is the target destination & B is the current destination. So when navigating from A -> B, forward transition will be played on A and backward transition will be played on B & vice-versa.

controller.navigateTo(dest) {
    withAnimation {
        target = SlideRight
        current = Fade
    }
}

Navigate with single top instance or popUpTo

controller.navigateTo(dest) {
    singleTop = true // makes sure that there is only one instance of this destination in backstack.
}
controller.navigateTo(dest) {
    popUpTo(dest) { // recursivly pops the backstack till the destination.
        inclusive = true // inclusive
        all = false // last added one will be chosen.
    }
}

Implementing Nested Navigation

When you call navigator.Setup, it binds the current ComposeNavigator to the CompositionLocal which can be retrived using findComposeNavigator(). It also binds the Controller<T> associated with the destination T for all the child composables which can be retrieved using findController<T>().

All you have to do is implement navigator.Setup for another screen where you want nested-navigation.

Check out the Basic Sample for a more clear example.

@Composable
fun SecondScreen() { // nested to MainScreen
    val mainController = findController<MainRoute>() // controller associated with MainRoute.
    val navigator = findComposeNavigator()
    navigator.Setup(key = SecondRoute.key, initial = SecondRoute.First()) { controller, dest ->
        when(dest) {
            ...
        }
    }
}
Clone this wiki locally