您可以使用内置的类型安全 API 为导航图提供编译时类型安全。如果您的应用使用 Navigation Compose 或 Navigation Kotlin DSL,这些 API 可用。它们从 Navigation
2.8.0
开始提供。
这些 API 相当于 Safe Args 为导航图内置导航 XML 资源文件提供的 API
定义路由
如需在 Compose 中使用类型安全路由,您首先需要定义表示路由的可序列化类或对象。
- 对象:针对没有实参的路线使用对象。
- Class:为包含参数的路线使用类或数据类。
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>
目的地。可以使用 NavBackStackEntry.toRoute
重构 Profile
并读取其属性,以获取任何导航参数(例如 id
)。