A lightweight library to help you navigate in compose with well typed functions.
You can add this library to your project by just adding the following code to your root build.gradle
allprojects {
repositories {
// ...
maven { url 'https://jitpack.io' }
}
}
Then import the library in your app build.gradle
file.
implementation 'com.github.xmartlabs:TypedNavigation:0.0.4'
You just have to define your screens and the arguments they receive:
object Router {
val default = TypedNavigation.E("default")
val sample = TypedNavigation.A3("sample", NavType.StringType, NavType.StringType, NavType.StringType)
}
And after that the library will provide you with the following functions:
To add your screen to the NavHost
:
setContent {
val navigationController: NavHostController = rememberNavController()
NavHost(navController = navigationController, startDestination = Router.default.url) {
composable(Router.default) {
Default(navigationController = navigationController)
}
composable(Router.example) { a: String?, b: String?, c: String? ->
Example(a, b, c)
}
}
}
To navigate from one screen to another:
navigationController.navigate(Router.example.route("a", "b", "c"))
Add deep linking to your screen by setting up the correct path to the url:
val example =
TypedNavigation.A3("example", NavType.StringType, NavType.StringType, NavType.StringType,
listOf { a1, a2, a3 -> // a1, a2 and a3 contains the keys for the attributes previously defined
"www.example.com/$a1/$a2/$a3"
}
)
You can access attributes stored in the SavedStateHandle
by using withAttributes
@HiltViewModel
class HiltExampleViewModel @Inject constructor(
savedStateHandle: SavedStateHandle
) : ViewModel() {
data class ScreenState(val name: String? = null, val age: Int? = null, val knowsHilt: Boolean? = null)
val stateFlow: MutableStateFlow<ScreenState> = MutableStateFlow(ScreenState())
init {
Router.hiltExample.withAttributes(savedStateHandle) { name, age, knowsHilt ->
viewModelScope.launch {
stateFlow.emit(ScreenState(name!!, age, knowsHilt))
}
}
}
}
For more examples you can check out our example app.
Made with ❤️ by XMARTLABS