在多模块应用中使用navigation不知不觉都是这么用
https://www.youtube.com/watch?v=lv1raAvwcgI&t=318s
省流总结:
假设我们有主模块 app, 功能模块 featureA, featureB,
featureA中有 screen1, screen2
featureB中有 screen3, screen4
核心common模块定义了Route1->screen1,Route2->screen2,Route3->screen3.....
如果在screen3 中要跳转到A中的screen1
有时候代码会是这样
@Composable
fun Screen3(navController: NavController,modifier: Modifier = Modifier
) {Box(modifier = Modifier.fillMaxSize(),contentAlignment = Alignment.Center) {Button(onClick = {navController.navigate(Route.Screen1)} ) {Text("Go to Screen 1")}}
}
我们把导航逻辑写到模块中带来的问题是,
如果我现在单独使用 featureB,但是featureB中因为导航的这个逻辑,又要不得不去关联featureA。
所以,需要把导航的逻辑到需要通过lambda来提升到外部去
@Composable
fun ScreenA(onButtonClick: () -> Unit,modifier: Modifier = Modifier
) {Box(modifier = Modifier.fillMaxSize(),contentAlignment = Alignment.Center) {Button(onClick = onButtonClick //抛出导航逻辑) {Text("Go to Screen 1")}}
}
所有的逻辑写在应用nav模块中
NavigationMultiModulePrepTheme {Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->val navController = rememberNavController()NavHost(navController = navController,startDestination = Route.ScreenA) {composable<Route.Screen1> {Screen1(onButtonClick = {navController.navigate(Route.Screen3)})}composable<Route.Screen2> {Screen2(onButtonClick = {navController.navigate(Route.Screen3)})}composable<Route.Screen3> {Screen3(onButtonClick = {navController.navigate(Route.Screen1) {popUpTo<Route.Screen3> {inclusive = true}}})}}}}
所以,我们不该在内部的功能部分看到navigate的导航逻辑