How to use Safe Args in an Android app?

Safe Args is a Gradle plugin that provides type-safe access to navigation actions and arguments when using the Android Jetpack Navigation component. It helps to eliminate the issues with passing data between fragments, allowing developers to define and access parameters safely and conveniently.

How to Use Safe Args in an Android App

  1. Add Safe Args Plugin: In your project-level build.gradle file, include the Safe Args Gradle plugin.
  2. Apply the Plugin: In your app-level build.gradle file, apply the Safe Args plugin.
  3. Set Up Navigation Graph: Create a navigation graph XML file that outlines your app's navigation structure.
  4. Add Actions and Arguments: Define actions and their arguments in the navigation graph.
  5. Generate Classes: Build your project to generate the necessary classes for safe argument passing.
  6. Access Arguments: Use the generated classes in your fragments to access the arguments safely.

Example Code

// In your navigation graph (res/navigation/nav_graph.xml) // In your FirstFragment.kt val action = FirstFragmentDirections.actionFirstFragmentToSecondFragment("Hello, World!") findNavController().navigate(action) // In your SecondFragment.kt val args: SecondFragmentArgs by navArgs() val receivedArgument = args.arg1

Safe Args Android Navigation Type-safe Argument Passing Jetpack Navigation Android Development