您可以使用內建的類型安全 API,為導覽圖提供編譯時間類型安全。如果您的應用程式使用 Navigation Compose 或 Navigation Kotlin DSL,即可使用這些 API。自 Navigation
2.8.0
起開放訂購。
這些 API 相當於 Safe Args 在內建導覽 XML 資源檔案中的導覽圖提供的功能
定義路徑
如要在 Compose 中使用類型安全路徑,您必須先定義可排序的類別或物件,以代表路線。
- 物件:使用物件處理沒有引數的路徑。
- 類別:使用類別或資料類別處理含有引數的路徑。
KClass<T>
:如果不需要傳遞引數 (例如不含參數的類別,或是所有參數都含有預設值的類別),請使用這個選項。- 例如:
Profile::class
- 例如:
無論是哪一種情況,物件或類別都必須可以序列化。
例如:
// Define a home route that doesn't take any arguments
@Serializable
object Home
// Define a profile route that takes an ID
@Serializable
data class Profile(val id: String)
建立圖表
接下來,您需要定義導覽圖。使用 composable()
函式,將可組合項定義為導覽圖中的目的地。
NavHost(navController, startDestination = Home) {
composable<Home> {
HomeScreen(onNavigateToProfile = { id ->
navController.navigate(Profile(id))
})
}
composable<Profile> { backStackEntry ->
val profile: Profile = backStackEntry.toRoute()
ProfileScreen(profile.id)
}
}
請看以下範例:
composable()
會使用類型參數。也就是composable<Profile>
。- 與在
composable("profile")
中傳遞route
字串相比,定義目的地類型會更加可靠。 - 路徑類別會定義每個導覽引數的類型 (如
val id: String
所示),因此無需使用NavArgument
。 - 如果是設定檔路徑,
toRoute()
擴充功能方法會從NavBackStackEntry
及其引數重新建立Profile
物件。
如要進一步瞭解一般設計圖表的方式,請參閱設計導覽圖頁面。
前往輸入安全路徑
最後,您可以使用 navigate()
函式傳入路徑的執行個體,以便前往可組合項:
navController.navigate(Profile(id = 123))
將使用者導向導覽圖中的 composable<Profile>
目的地。任何導覽引數 (例如 id
) 都可以透過 NavBackStackEntry.toRoute
重新建構 Profile
並讀取其屬性的方式取得。