kotlin 我想找到一个更好的方法来使用NavHostController在撰写

wf82jlnq  于 2023-05-01  发布在  Kotlin
关注(0)|答案(1)|浏览(195)
@Composable
fun AppPage() {
    val navController = rememberNavController()
    //first way
    Page1(navController)
    //second way
    Page3 {
        navController.navigate("AnyRoute")
    }
}

@Composable
fun Page1(navController: NavHostController) {
    //do anything
    Page2(navController = navController)
}

@Composable
fun Page2(navController: NavHostController) {
    navController.navigate("AnyRoute")
}

@Composable
fun Page3(toLogin: () -> Unit) {
    //do anything
    Page4 {
        toLogin.invoke()
    }
}

@Composable
fun Page4(toLogin: () -> Unit) {
    Text(text = "test", modifier = Modifier.clickable {
        toLogin.invoke()
    })
}

我认为这两种方法都不太好。这两种都容易导致方法中参数过多,尤其是第二种,我觉得很麻烦。有没有好的方法,用导航来导航

erhoui1w

erhoui1w1#

这就是我的导航方式。我尽我所能把它应用到你的例子中。

In your Main Activity. Pass to the Navigator any parameters your screens will need such as viewModels.

val navController = rememberNavController()
Navigator(navController, toLogin: () -> Unit)

Create a file like below with an object for each screen you want.
sealed class Screens(val route: String) {
    object Page1: Screens("Page1")
    object Page2: Screens("Page2")
    object Page3: Screens("Page3")
    object Page4: Screens("Page4")
}

Create a composable as follows. The startDestination is what screen the app will open to when started.
@Composable
fun Navigator (navController: NavHostController,
              ) {
    NavHost(
        navController = navController,
        startDestination = Screens.Page1.route)
    {
        composable(route = Screens.Page1.route){
            Page1(viewModel, navController)
        }
        composable(route = Screens.Page2.route){
            Page2(viewModel, navController)
        }
        composable(route = Screens.Page3.route){
            Page3(viewModel, navController)
        }
        composable(route = Screens.Page4.route){
            Page4(viewModel, navController)
        }
    }
}

From any of your composables you can navigate to another with this.
navController.navigate(Screens.Page3.route)

相关问题