This library will make it easier to pass arguments between screens in Jetpack Compose
Copy allprojects {
repositories {
.. .
maven { url 'https://jitpack.io' }
}
}
dependencies {
implementation 'com.github.doctor-blue:compose-navigation:1.1.0'
}
Step 1: Create your screen class and extend it with ComposeScreen class
Copy mport com.devcomentry.lib.ComposeScreen
sealed class Screen (_route: String ) : ComposeScreen ( _route ) {
object MainScreen : Screen ( "main_screen" )
object Screen1 : Screen ( "screen1" )
object Screen2 : Screen ( "screen2" )
}
Step 2: Create a class and implement it with Argument interface. Variables in this class is your argument you wanna pass to other screen.
Copy package com.devcomentry.composenavigation.ui.screen
import com.devcomentry.lib.Argument
data class Screen2Argument ( val number: Int = - 1 ) : Argument
Step 3: Setup your navigation
Copy package com.devcomentry.composenavigation
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.rememberNavController
import com.devcomentry.composenavigation.ui.screen.*
import com.devcomentry.lib.composable
import com.devcomentry.lib.from
class MainActivity : AppCompatActivity () {
override fun onCreate (savedInstanceState: Bundle ?) {
super . onCreate (savedInstanceState)
setContent {
Surface {
Surface (
color = MaterialTheme.colors.background,
) {
val navController = rememberNavController ()
NavHost (
navController = navController,
startDestination = Screen.MainScreen.route
) {
composable (Screen.MainScreen) {
MainScreen (navController = navController)
}
composable (Screen.Screen1) {
Screen1 ()
}
composable (Screen.Screen2, Screen2Argument ()) {
// get data from arguments
it.arguments?. let { bundle ->
val argument = Screen2Argument (). from (bundle)
Screen2 (argument)
}
}
}
}
}
}
}
}
Step 4: Navigate to other screen
Copy navController. navigate (Screen.Screen1.route)
Copy navController. navigate (
Screen.Screen2. setParam (
Screen2Argument (
Random. nextInt (
0 ,
50
)
)
)
)
Copy val argument = Screen2Argument (). from (bundle)
// use your argument
Copy val argument = Screen2Argument (). from (savedStateHandle)
// use your argument