Reputation: 879
StackOverflow community!
I'm facing an issue with Jetpack Compose navigation using NavHost and rememberNavController. My app works as expected most of the time, but occasionally, when I tap buttons to switch between screens, the content disappears, and only the Surface remains visible.
Here's a simplified version of my code:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val navController = rememberNavController()
NavigationTestTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = Color.Cyan
) {
NavHost(navController = navController, startDestination = "First") {
composable(route = "First") {
FirstScreen(onButtonTap = { navController.navigate("Second") })
}
composable(route = "Second") {
SecondScreen(onButtonTap = { navController.popBackStack() })
}
}
}
}
}
}
}
@Composable
fun FirstScreen(onButtonTap: () -> Unit) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.fillMaxSize()
.background(Color.Blue)
) {
CustomButton(title = "To Second View") {
onButtonTap()
}
}
}
@Composable
fun SecondScreen(onButtonTap: () -> Unit) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.fillMaxSize()
.background(Color.Green)
) {
CustomButton(title = "Pop View") {
onButtonTap()
}
}
}
@Composable
fun CustomButton(title: String, onClick: () -> Unit) {
Button(
onClick = { onClick() },
modifier = Modifier.size(width = 200.dp, height = 40.dp)
) {
Text(text = title)
}
}
The expected behavior is:
However, sometimes when I tap buttons on both FirstScreen and SecondScreen to switch views, the views get removed from the back stack, and only the Surface with the Cyan color remains visible.
I've tried simplifying the code and isolating the issue, but I can't seem to pinpoint the root cause. Any suggestions or insights into what might be causing this issue would be greatly appreciated.
Thank you in advance for your help!
Upvotes: 0
Views: 498
Reputation: 879
It turns out the problem was I used popBackStack
to dismiss the current view. Instead, I used navigateUP, and worked well.
Upvotes: 0