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()
},
)
}
}
CodePudding user response:
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.
CodePudding user response:
it's depends how are you back to the home screen. if you use navController.navigete("home")
then
@Composable
HomeScreen() {
LaunchedEffect(key1 = true) {
Log.i("HomeScreen", "home screen visible")
// call your methods here
}
// the rest of HomeScreen code
}
it will work fine.
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.navigete("home")
example - >
navController.popBackStack()
navController.navigete("home")