Skip to content

Instantly share code, notes, and snippets.

@tfcporciuncula
Last active April 23, 2024 11:51
Show Gist options
  • Save tfcporciuncula/ef0698c238ea7d2431c548671ec8b271 to your computer and use it in GitHub Desktop.
Save tfcporciuncula/ef0698c238ea7d2431c548671ec8b271 to your computer and use it in GitHub Desktop.
Getting arg directly from navBackStackEntry
@Composable
fun StartScreen(onNavigateClick: (String) -> Unit) {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
var argText by rememberSaveable { mutableStateOf("") }
TextField(
value = argText,
onValueChange = { argText = it },
)
Button(
onClick = { onNavigateClick(argText) },
modifier = Modifier.padding(top = 16.dp),
enabled = argText.isNotBlank(),
) {
Text(text = "Navigate with arg")
}
}
}
@Composable
fun DetailsScreen(arg: String) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center,
) {
Text(
text = arg,
style = typography.headlineMedium,
)
}
}
@Composable
fun App(
modifier: Modifier = Modifier,
) {
Box(
modifier = modifier
.fillMaxSize()
.background(color = colorScheme.background),
) {
val navController = rememberNavController()
NavHost(navController = navController, startDestination = "start") {
composable(route = "start") {
StartScreen(
onNavigateClick = { arg -> navController.navigate(route = "details/$arg") },
)
}
composable(route = "details/{arg}") { navBackStackEntry ->
val arg = requireNotNull(navBackStackEntry.arguments?.getString("arg"))
DetailsScreen(arg = arg)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment