Wear Compose类型安全导航中SwipeDismissableNavHost startDestination报错求助
问题
如何在Wear Compose中使用类型安全版本的Navigation库?发现SwipeDismissableNavHost的startDestination属性无法像NavHost那样接受Any类型的值。
使用的Wear Compose导航依赖:androidx.wear.compose:compose-navigation:1.5.0-alpha04
报错信息:
java.lang.IllegalArgumentException: navigation destination home is not a direct child of this NavGraph
代码示例:
@AndroidEntryPoint class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { installSplashScreen() super.onCreate(savedInstanceState) setTheme(android.R.style.Theme_Black) setContent { WearAppIMSTheme { Scaffold(timeText = { TimeText( timeTextStyle = TimeTextDefaults.timeTextStyle( color = MaterialTheme.colors.onBackground ) ) }, content = { DemoApp(modifier = Modifier) }) } } } } @Composable fun DemoApp(modifier: Modifier) { Box( modifier = modifier .background(MaterialTheme.colors.background) ) { val navController = rememberSwipeDismissableNavController() /** * NavHost Builds a navGraph to handle navigation, set the start destination to Home and * provide the navController which will control the navigation. */ SwipeDismissableNavHost( navController = navController, startDestination = ("home") // Getting Error: IllegalArgumentException: navigation destination home is not a direct child of this NavGraph ) { composable<Routes.Home> { Home(navigateToDetails = { aptDetails -> navController.navigate(Routes.AppointmentDetail(aptDetails)) }, navigateToMySchedule = { navController.navigate(Routes.MySchedule) }, navigateToWaitingApts = { navController.navigate(Routes.WaitingForMe) }) } composable<Routes.WaitingForMe> { WaitingForMe(onBackPress = { navController.popBackStack() }) } composable<Routes.AppointmentDetail>( typeMap = mapOf(typeOf<ApptList>() to NavType.fromCustom<ApptList>()) ) { val apptList = rememberSaveable { it.toRoute<Routes.AppointmentDetail>().apptDetail } AppointmentDetail(apptList, onBackPress = { navController.popBackStack() }, modifier) } composable<Routes.MySchedule> { MySchedule(onBackPress = { navController.popBackStack() }, modifier = Modifier, navigateToDetails = { navController.navigate(Routes.AppointmentDetail(it)) }) } } } }
解决方案
错误原因
你使用字符串"home"作为startDestination,但导航图中注册的是类型安全的路由对象Routes.Home,两者不匹配导致系统无法找到对应导航目标,从而抛出异常。
修复步骤
- 替换startDestination的值:直接用类型安全的路由对象
Routes.Home替代字符串"home",和导航图中注册的路由保持一致。 - 保持导航操作一致性:所有导航调用(比如
navController.navigate())都使用类型安全的路由对象,避免混用字符串和路由对象。
修改后的关键代码
SwipeDismissableNavHost( navController = navController, startDestination = Routes.Home // 替换为类型安全的路由对象 ) { // 导航图内容保持不变 }
修改后SwipeDismissableNavHost就能正确识别起始目标,类型安全导航可正常工作。
内容的提问来源于stack exchange,提问作者Vishal
相关产品推荐
相关产品推荐

