Now is time for your first challenge in this part. For this, I want you to add the back button functionality in the TopAppBar of the Scaffold and the back Button in the main content inside the AboutScreen. You’ll be following the same process of state hoisting from the previous episode.
You’ll name the exposed event for the AboutScreen composable onNavigateBack. Call it inside the onClick listener of the IconButton and Button composables. Then inside the MainScreen composable, you’ll call the navigateUp() method of the navController instance.
Alright, all the best on this one.
That was pretty straightforward I believe. If you didn’t figure it out, that’s okay too. Let me show you my solution and you could see what you might have missed out.
First, I’ll open up the AboutScreen.kt file.
Then add the onNavigateBack parameter which is a lambda without parameters that returns nothing:
fun AboutScreen(onNavigateBack: () -> Unit) {
//...
}
Then I’ll call it in the onClick listener of the IconButton and the back Button in the content:
// In the TopAppBar
IconButton(onClick = { onNavigateBack() }) {
//...
}
// In the Button in the main content
Button(
onClick = { onNavigateBack() },
//...
) {
//..,.
}
This onNavigateBack() event will be triggered whenever these buttons are tapped. Let’s add in an empty call for it in the preview composable:
AboutScreen(onNavigateBack = {})
Then I’ll head over to the MainScreen composable in the MainActivity.kt file. And you can see the AboutScreen call complaining that it also needs this parameter.
I’ll update it to the following:
composable("about") {
AboutScreen(onNavigateBack = { navController.navigateUp() }) // Updated Code
}
The navController.navigateUp() method pops the current composable from the navigation stack and takes us back to the previous screen, in this case the GameScreen.
I’ll run the app.
Tap the info button. Then tap the back button up in the TopAppBar. And it takes us back as expected. I’ll tap the info button once again. Then tap the back button in the main content area.
Cool!!! Everything works as expected and we have a good navigation flow working in Bullseye.