Sobes.tech
Junior — Middle

What methods can be used to transfer data between screens when using Jetpack Compose Navigation?

sobes.tech AI

Answer from AI

In Jetpack Compose Navigation, there are several approaches to passing data between screens:

  1. Navigation Arguments
    • You can specify parameters in the route declaration that will be passed to the next screen.
    • Primitive types and strings are supported.
    • Example of passing an id:
navController.navigate("detail_screen/$itemId")

composable("detail_screen/{itemId}") { backStackEntry ->
    val itemId = backStackEntry.arguments?.getString("itemId")
    DetailScreen(itemId)
}
  1. Shared ViewModel

    • Using a ViewModel that lives at the navigation graph or activity level.
    • Both screens access the same ViewModel instance and can exchange data through it.
  2. State Hoisting

    • Passing state via parameters of screen functions.
    • Suitable for small data and when screens are within the same component.
  3. Saving data in NavBackStackEntry.savedStateHandle

    • You can put data into savedStateHandle before returning to the previous screen.
    • Allows passing data back.

Example of using savedStateHandle:

// Passing data back
navController.currentBackStackEntry?.savedStateHandle?.set("key", value)

// Retrieving data in the previous screen
val savedStateHandle = navController.previousBackStackEntry?.savedStateHandle
val value = savedStateHandle?.get<String>("key")

Thus, the choice of method depends on the type and volume of data, as well as the architecture of the application.