From the course: Android Compose with Kotlin

Navigate between screens - Kotlin Tutorial

From the course: Android Compose with Kotlin

Navigate between screens

- [Instructor] We have our navigation host set up to support our composable destinations, however, we haven't supplied a UI element that will allow the navigation to take place. Let's do that now. We'll modify the SessionScreen to navigate to the speaker screen, and we'll start with adding simply an ElevatedButton. We'll come first to the SessionsScreen parameters, and we'll add a new one, which we'll name onButtonClick. And this is simply going to be a lambda that returns Unit, so nothing. Next, we'll add an ElevatedButton to our column composable, so simply here. And for the onClick property, we'll set it equal to our onButtonClick parameter. And the final step is to add a text composable for what we want to show. And let's set that text equal to our speakers label. So we'll grab that from stringResources, and that's R.string.speakers_label. Okay, let's bring in that import. Sometimes that import gives me a hard time, so I'll just scroll up to the top with our imports and I'll add it in directly. So let's just import our full package name. Okay, perfect. We'll add one more parameter here, and that's the style, just so we can make the text a bit larger. And we'll set that equal to our MaterialTheme.typography, and let's do titleLarge. And let's make sure we haven't missed anything. So we're getting an error down here in our preview, that's because we haven't passed in the onButtonClick property. So what I like to do in this case is just set it equal to a default, which is just an empty lambda, and that tends to fix it. When we look over here in our preview, we see our Speakers button. Great. We now have one more change that we need to make to take advantage of this onButtonClick parameter, and that's back in our nav host, so we'll move there. And we want to use this for the SessionsScreen. So we're passing in uiState, and we'll now pass in one more parameter value, which is onButtonClick. And we're going to set that equal to a call to our navController. We're going to use its navigate function, and for the input, we'll pass in the speakers route. And the strings have to match exactly. So the same string we use on line number 38, we're going to use that here on line number 34. And then, we'll run the app. Okay, like before, we have all of our list of sessions, but at the very top, we have the Speakers button. When we click on it, it takes us to our SpeakersScreen, which contains currently a list of all of the speaker's names. And when we click Back, we're taken right back to the SessionScreen. When I first started programming on Android over a decade ago, doing this simple task took dozens of lines of code, oh, and endless debugging. Now with the navigation component in Compose, there are only minor additions, and our users enjoy a smooth navigation experience.

Contents