Kotlin DSL 和 Navigation Compose 中的类型安全

您可以使用内置的类型安全 API 为导航图提供编译时类型安全。如果您的应用使用 Navigation ComposeNavigation Kotlin DSL,这些 API 可用。它们从 Navigation 2.8.0开始提供。

这些 API 相当于 Safe Args 为导航图内置导航 XML 资源文件提供的 API

定义路由

如需在 Compose 中使用类型安全路由,您首先需要定义表示路由的可序列化类或对象。

  • 对象:针对没有实参的路线使用对象。
  • Class:为包含参数的路线使用类或数据类。
  • KClass<T>:如果您不需要传递参数(例如不带形参的类,或所有形参都具有默认值的类),请使用此选项
    1. 例如: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)。

其他资源