val scoreFragmentArgs1 by navArgs<ScoreFragmentArgs>()
val scoreFragmentArgs2 = ScoreFragmentArgs.fromBundle(arguments!!)
I'm able to access the arguments that was passed from the previous fragment using any of above statements. Can someone explain the difference and when to use each. Thanks in advance
The second call is the simpler one. That one's eagerly evaluated whenever that line runs, so it will require the arguments
bundle to be already in place, as well as contain all the keys that you expect to be in it.
The first approach gives you a lazily created Args
instance instead, which will only be initialized when you first try reading its value. Therefore it's safe to declare it at the class level. See navArgs
in the docs for all the details. The most important parts:
It is strongly recommended that this method only be used when the Activity is started by
androidx.navigation.NavController.navigate
with the correspondingandroidx.navigation.NavDirections
object, which ensures that the required arguments are present.This property can be accessed only after the
Activity
is attached to the Application, and access prior to that will result inIllegalStateException
.