Prerequisite
- Basic understanding of Jetpack compose
- Familiarity with the navigation system of compose
Suggested reads
Jetpack compose has been out for a while now and so is the navigation system, it’s simple and direct.
A simple implementation of navigation would look something like
The above code would work fine, but let’s be careful with two things.
- Hard-coded strings
- Passing instance of
navController
to every composable
Let’s organize string literals.
We can still improve this by leveraging Kotlin’s feature to use. Let’s create a Sealed class now.
This looks clean. Now let’s fix the strings for arguments.
This is as clean as it gets, now let’s try to make sure that we don’t have to pass an instance of navController
everywhere.
Let’s create a class that works as a wrapper over navController
This seems good, now let’s see how can we actually use it in our code.
And our Navigation-related code can stay in one file.
This way we can keep our strings private
at the same time, we can make sure our constants are all at the same place and make sure we are not exposing the instance of navController
directly everywhere.
The above-mentioned guide can help you fix a few things in your code.
- Making sure your string literals are private and maintained in a single place.
- Abstracting the instance of
navController
by using a wrapper class.
To see this code in action, you can check out this repository
I hope this article was informative and helped you clean up your navigation code. Feel free to share your feedback or queries.