通过组合导航传递Parcelable参数 [英] Pass Parcelable argument with compose navigation

查看:92
本文介绍了通过组合导航传递Parcelable参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用组合导航将可打包对象( BluetoothDevice )传递给可组合对象.

I want to pass a parcelable object (BluetoothDevice) to a composable using compose navigation.

传递基本类型很容易:

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

navController.navigate("profile/user1234")

但是,除非将其序列化为字符串,否则我无法在路由中传递可包裹对象.

But I can't pass a parcelable object in the route unless I can serialize it to a string.

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

val device: BluetoothDevice = ...
navController.navigate("deviceDetails/$device")

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

The code above obviously doesn't work because it just implicitly calls toString().

有没有一种方法可以将 Parcelable 序列化为 String ,这样我就可以在路线中传递它,或者将导航参数作为对象传递给具有其他功能的对象 navigate(route:String)?

Is there a way to either serialize a Parcelable to a String so I can pass it in the route or pass the navigation argument as an object with a function other than navigate(route: String)?

推荐答案

编辑:已更新为 beta-07

基本上,您可以执行以下操作:

Basically you can do the following:

// 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")

这篇关于通过组合导航传递Parcelable参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆