简体   繁体   中英

compose navigation handle when composable returned after back

Let's say I have 2 screens HomeScreen and DetailScreen and use compose navigation to navigate between screens.

The graph is HomeScreen -> DetailScreen .

When I pressed back on DetailScreen and returned to HomeScreen I want HomeScreen reacted to that and had to call some method. I want HomeScreen composable to call some method every time he shows up on the screen. How to achieve that?

NavHost(
        navController = navController,
        startDestination = "Home"
    ) {
        composable("Home") {
            HomeScreen(
                onDetailClick= {
                    navController.navigate("Detail")
                }
            )
        }
        composable("Detail") {
            DetailScreen(
                onBackClick= {
                    navController.popBackStack()
                },
            )
        }
}

You should use NavHostController.navigateUp() instead of NavHostController.popBackStack() , then you can use LaunchedEffect with a fixed value like Unit for the key.

@Composable
HomeScreen() {
    LaunchedEffect(key1 = Unit) {
        Log.i("HomeScreen", "home screen visible")

        // call your methods here
    }
    
    // the rest of HomeScreen code
}

But be careful because everytime configuration change occured it will also be re-executed.

It depends how are you back to the home screen. If you use navController.navigete("home") then it will work fine.

@Composable
HomeScreen() {
    LaunchedEffect(key1 = true) {
        Log.i("HomeScreen", "home screen visible")

        // call your methods here
    }
    
    // the rest of HomeScreen code  
}

Or, if you are using navController.popBackStack() , then it will not work.

For that, you need to first navigate to Home by using navController.popBackStack() then use navController.navigate("home")

example - >

navController.popBackStack()
navController.navigete("home")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM