I am trying navigation in Android Jetpack Compose. But the problem is when I try to get the parameter using navBackStackEntry
it always gives null
or the default value which I have set.
I am using following gradle dependencies for navigation:
implementation "androidx.navigation:navigation-compose:2.7.1"
Here is the complete code for the reference:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
TryingSomethingTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
val navController = rememberNavController()
NavHost(
navController = navController,
startDestination = "profile/12345"
) {
composable(
route = "profile/{id}",
arguments = listOf(
navArgument("id") {
type = NavType.StringType
defaultValue = "invalid"
}
)
) {
Log.d("MyTag", "id: ${it.arguments?.getString("id")}")
}
}
}
}
}
}
}
I guess that you are just experimenting. It is not recommended to use a dynamic value in the Start Destination. In fact, the dynamic value you use here, 12345, should be the defaultValue
you gave. If you try navigate
, you can access the ID
.
navController.navigate("profile/1234")
But if this is something you specifically want, you can find alternative solutions in previously answered questions here. You can try them, but I believe you are just experimenting.
Jetpack Compose Navigation - pass argument to startDestination