问题
say I have 2 fragments. Login and Home. I set Home fragment as a global destination that has userData as arguments
if the user is not logged in yet, then it will start from login fragment. after login and get userData from server then it will navigate to Home and pass userData using this code
val home = AuthenticationFragmentDirections.actionGlobalHomeFragment(userData)
Navigation.findNavController(view).navigate(home, navOptions)
but the problem is when the user already login and open the app. in this situation they will directly open the home fragment. and I my app crash with error
java.lang.IllegalArgumentException: Required argument "userData" is missing and does not have an android:defaultValue
so I assume I can set nullable data type in arguments like User?
, so the Home fragment doesn't need userData if it doesn't come from Login
after reading from here, I set the argument like this to achieve User?
<argument
android:name="userData"
android:defaultValue="@null"
app:argType="User"
app:nullable="true" />
but the problem is, it said that I have too many arguments when I put user data to be sent to home from Login fragment
I use this in the gradle
implementation "androidx.navigation:navigation-fragment-ktx:2.3.0-alpha04"
implementation "androidx.navigation:navigation-ui-ktx:2.3.0-alpha04"
回答1:
When using apply plugin: "androidx.navigation.safeargs"
, only required arguments are passed to the actionGlobalHomeFragment()
method - arguments with default values (i.e., ones that aren't required) are passed with the generated set
methods:
val home = AuthenticationFragmentDirections.actionGlobalHomeFragment()
.setUserData(userData)
Navigation.findNavController(view).navigate(home, navOptions)
If you were to switch to generating Kotlin Safe Args code by applying apply plugin: "androidx.navigation.safeargs.kotlin"
(note the .kotlin
), then the code uses Kotlin default arguments (i.e., with userData: UserData = null
in the method declaration), which does let you use the syntax you were initially trying:
val home = AuthenticationFragmentDirections.actionGlobalHomeFragment(userData)
Navigation.findNavController(view).navigate(home, navOptions)
来源:https://stackoverflow.com/questions/60807867/can-i-send-nullable-data-type-as-argument-using-safeargs-if-not-what-should-i