Reputation: 176
I have this enum
enum class AppScreen(@StringRes val title: Int) {
Index(title = R.string.app_name),
Detail(title = R.string.app_name)
}
and a Composable function with the navigation logic
composable(route = AppScreen.Index.name){
IndexScreen(
onNavigate = { id ->
Log.d(TAG, "id: " + id.toString())
navController.navigate(
route = "${AppScreen.Detail.name}?id=$id",
)
}
)
}
composable(
route = "${AppScreen.Detail.name}/{id}",
arguments = listOf(
navArgument("id") {
type = NavType.IntType
}
)
){
val id = it.arguments?.getInt("id") ?: -1
DetailScreen(id)
}
The Index screen is a list of items. When I click one of the items, the application crash. The Log with the item id is printed, but after there is the error:
java.lang.IllegalArgumentException: No enum constant com.utils.AppScreen.Detail/{id}
EDIT
I solved by changing the declaration of the Enum
sealed class AppScreen(
val route: String,
@StringRes val title: Int
) {
object Index: AppScreen("Index", R.string.index)
object Detail: AppScreen("Detail/{id}", R.string.detail) {
fun createRoute(id: Int) ="Detail/$id"
}
}
and then the Composable function
composable(route = AppScreen.Index.route){
IndexScreen(
onNavigate = { id ->
navController.navigate(
route = AppScreen.Detail.createRoute(id),
)
}
)
}
composable(
route = AppScreen.Detail.route,
arguments = listOf(
navArgument("id") {
type = NavType.IntType
}
)
){
val id = it.arguments?.getInt("id") ?: -1
DetailScreen(id)
}
Upvotes: 1
Views: 27
Reputation: 12963
You are not passing the id in the proper way try changing the line
route = "${AppScreen.Detail.name}?id=$id"
to
route = "${AppScreen.Detail.name}/$id"
Upvotes: 1