- Step 1 :-
This is my home screen function@Composable
fun HomeScreen(navController: NavHostController) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(
modifier = Modifier.padding(20.dp)
.clickable {
val person =Person("Roshan",25)
navController.currentBackStackEntry?.savedStateHandle?.set(
"data",person
)
navController.navigate(Screen.Profile.route)
},
text = "Welcome to Home Screen",
fontSize = MaterialTheme.typography.titleLarge.fontSize
)
}
} - Step 2 :- You have to get this in routing function
You can also use Launch Effect while getting data from prvious composable function or route.composable(route = Screen.Profile.route) {
val result=navController.previousBackStackEntry?.savedStateHandle?.get<Person>("data")
Log.e("roshan", "SetupNavGraph: ${result?.name} , ${result?.age}}" )
ProfileScreen(navController = navController)
} - Result :-
SetupNavGraph: Roshan , 25}
Now another method for passing data by using viewmodel - Step 1 :-
class SharedViewModel():ViewModel() {
var person by mutableStateOf<Person?>(null)
private set
fun addPerson(newPerson: Person){
person=newPerson
}
} - Step 2 :- From there, wherever you want to pass data
val person = Person("Roshan",25)
sharedPreference.addPerson(person) - Step 3 :-
For getting , you have to get like thisval person=sharedPreference.person
LaunchedEffect(key1 = person) {
Log.e("roshan", "ProfileScreen: ${person?.name}" )
Log.e("roshan", "ProfileScreen: ${person?.age}" )
} //Also navgraph should like this@Composable
fun SetupNavGraph(navController: NavHostController, startDestination: String) {
val sharedPreference:SharedViewModel= viewModel()
NavHost(
navController = navController,
startDestination = startDestination
) {
composable(route = Screen.Welcome.route) {
WelcomeScreen(navController = navController)
}
composable(route = Screen.Home.route) {
HomeScreen(navController=navController,sharedPreference)
}
composable(route = Screen.Splash.route) {
AnimatedSplashScreen(navController = navController)
}
composable(route = Screen.Profile.route) {
/*LaunchedEffect(key1 = it) {
val result=navController.previousBackStackEntry?.savedStateHandle?.get<Person>("data")
Log.e("roshan", "SetupNavGraph: ${result?.name} , ${result?.age}}" )
}*/
ProfileScreen(navController = navController,sharedPreference)
}
}
}
0 Comments