kotlin 如何使用jetpack compose navigation应用可选参数?

xoshrz7s  于 2023-10-23  发布在  Kotlin
关注(0)|答案(1)|浏览(138)

我读过:https://developer.android.com/jetpack/compose/navigation#optional-args
这是我的代码:

override fun getComposableSettings(): ComposableSettings {
        return ComposableSettings(
            route = "${BASE_ROUTE}?$ARG_SEARCH_TEXT_DEEPLINK={${ARG_SEARCH_TEXT_DEEPLINK}}",
            arguments = listOf(
                navArgument(ARG_SEARCH_TEXT_DEEPLINK) {
                    type = NavType.StringType
                    defaultValue = ""
                },
            )
        )
    }

这是我的路线:

fun getRoute(searchText: String = ""): String {
        return "${BASE_ROUTE}?$ARG_SEARCH_TEXT_DEEPLINK={${searchText}}"
    }

它可以工作,因为我的参数总是String和值:{},所以它不是空字符串,但总是有值,那么我需要删除这个括号,使其正常工作,并与下一个操作操作。对我来说,这是无稽之谈。它应该是可选参数,比如如果它是空的,它就和empty defaultValue一起,仅此而已。在这个文档示例中,添加了像test1234这样的值的字符串,所以它当然可以工作,因为它不是可选参数,而是强制使任何值。
问候

tzdcorbm

tzdcorbm1#

检查以下代码。它的工作原理是不在参数中传递任何值

@Composable
fun MyApp() {
    val context = LocalContext.current
    val navController = rememberNavController()

    NavHost(navController = navController, startDestination = "profile") {
        composable("profile") { Profile(navController, null) }
        composable(
            "friendslist?userId={userId}",
            arguments = listOf(navArgument("userId") { nullable = true })
        ) { backStackEntry ->
            FriendsList(navController, backStackEntry.arguments?.getString("userId"))
        }
    }
}

@Composable
fun Profile(navController: NavHostController, string: String?) {
    Log.d("MainActivity", "Profile: ")
    //Here the navigation to friendslist is not having any arguments
    navController.navigate("friendslist")

    //Here the navigation to friendslist with arguments
    navController.navigate("friendslist?userId=1234")
}

@Composable
fun FriendsList(navController: NavHostController, string: String?) {
    Log.d("MainActivity", "FriendsList: $string")
}

相关问题