使用撰写导航传递Parcelable参数

我想BluetoothDevice使用组合导航将 Parcelable 对象 ( ) 传递给可组合对象。

传递原始类型很容易:

composable(
  "profile/{userId}",
  arguments = listOf(navArgument("userId") { type = NavType.StringType })
) {...}
navController.navigate("profile/user1234")

但是我不能在路由中传递一个parcelable 对象,除非我可以将它序列化为一个字符串。

composable(
  "deviceDetails/{device}",
  arguments = listOf(navArgument("device") { type = NavType.ParcelableType(BluetoothDevice::class.java) })
) {...}
val device: BluetoothDevice = ...
navController.navigate("deviceDetails/$device")

上面的代码显然不起作用,因为它只是隐式调用toString().

有没有办法要么序列化ParcelableString,所以我可以通过它的路线或通过导航参数作为比其他函数的对象navigate(route: String)

回答

编辑:更新为beta-07

基本上你可以做到以下几点:

// In the source screen...
navController.currentBackStackEntry?.arguments = 
    Bundle().apply {
        putParcelable("bt_device", device)
    }
navController.navigate("deviceDetails")

在详细信息屏幕中...

val device = navController.previousBackStackEntry
    ?.arguments?.getParcelable<BluetoothDevice>("bt_device")

  • For anyone using this solution note the difference between currentBackStackEntry and previousBackStackEntry on either side of the navigate call. Otherwise you'll waste 20 mins looking for your missing data... ;0)
  • Note that this won't survive process death. https://issuetracker.google.com/issues/182194894#comment6

以上是使用撰写导航传递Parcelable参数的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>