https://kotlinlang.org logo
#getting-started
Title
# getting-started
c

Christopher Stocks

11/04/2021, 3:29 PM
Could anyone point me towards a method/library for handling navigation within Compose for Desktop?
t

Tobias Suchalla

11/05/2021, 6:59 AM
A very simple version could be:
Copy code
object AppState {
    var currentScreen: Screen by mutableStateOf(Screen.Screen1)
}

sealed class Screen {
    object Screen1 : Screen()
    object Screen2 : Screen()
    object Screen3 : Screen()
}

fun main(args: Array<String>) = singleWindowApplication {
    Root()
}

@Composable
fun Root() {
    Row {
        NavigationBar()
        when (AppState.currentScreen) {
            Screen.Screen1 -> Screen1()
            Screen.Screen2 -> Screen2()
            Screen.Screen3 -> Screen3()
        }
    }
}

@Composable
fun NavigationBar() {
    Column {
        Button({ AppState.currentScreen = Screen.Screen1 }) { Text("Screen1") }
        Button({ AppState.currentScreen = Screen.Screen2 }) { Text("Screen2") }
        Button({ AppState.currentScreen = Screen.Screen3 }) { Text("Screen3") }
    }
}

@Composable
fun Screen1() {
    Text("Screen1")
}

@Composable
fun Screen2() {
    Text("Screen2")
}

@Composable
fun Screen3() {
    Text("Screen3")
}
(Instead of
object Screen1 : Screen()
you could also do
data class Screen1(item: String) : Screen()
and pass around parameters that way). However, this approach does not keep track of a backstack, does not retain state and probably has a few other shortcomings.