Navigation ComposeでstartDestinationに引数を渡す方法

Kenji Abe
Oct 1, 2023

Photo by Clemens van Lay on Unsplash

Navigation Compose で最初の画面に引数を渡す方法についてです。
例えば、Activityのパラメータをそのまま Composable 関数に渡したい場合などがあります。そのときにどのようにすれば良いかを紹介します。

例えば、以下ように最初の画面に id パラメータを渡したい場合です。

NavHost(
navController = navController,
startDestination = "start/{id}"
) {
composable(
"start/{id}",
arguments = listOf(
navArgument("id") {
type = NavType.IntType
}
)
) { backStackEntry ->
val id = backStackEntry.arguments?.getInt("id")
// ...
}
}

まず startDestination に直接 start/123 のように渡せば動きそうですが、これでは引数を画面のほうから取得することができません。

NavHost(
navController = navController,
startDestination = "start/123" // <= ココ (これはうまく動かない)
) {
// ...
}

startDestination に引数を渡したい場合は、以下のように defaultValue を使って渡すことができます。

NavHost(
navController = navController,
startDestination = "start/{id}"
) {
composable(
"start/{id}",
arguments = listOf(
navArgument("id") {
type = NavType.IntType
defaultValue = 123 // <= ここに最初の画面の引数を設定する
}
)
) { backStackEntry ->
val id = backStackEntry.arguments?.getInt("id")
// ...
}
}

これで最初の画面に引数を渡すことができます。

なぜ引数として渡したいのか?

他の方法として思いつくことは、直接 Composable 関数に引数を渡す方法です。

NavHost(
navController = navController,
startDestination = "start"
) {
composable("start") {
StartScreen(id = 123) // <= 直接渡す
}
}

これでも良いのですが、この方法では ViewModel から SavedStateHandle から取得することはできなくなります。

ViewModelで引数を直接扱いたい場合などでは defaultValue を使う必要があります。

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Kenji Abe
Kenji Abe

Written by Kenji Abe

Programmer / Gamer / Google Developers Expert for Android, Kotlin / @STAR_ZERO

No responses yet

Write a response