I have setup navigation with NavHost
, passing data between screens happens via NamedNavArgument
.
The API I have returns player names like “username#123123”. the problem is that if this value is passed to navController
then it only saves “username”. Any way to pass whole value?
I could replace # with some other char, but this looks like a extra logic. what if # is just one of many other chars?
Here is full code in a single file
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
OversearchTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
App()
}
}
}
}
}
@Composable
fun App() {
val navController = rememberNavController()
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
NavHost(navController = navController, startDestination = HOME) {
composable(HOME) {
Button(modifier = Modifier.wrapContentHeight(), onClick = {
navController.navigate("$PLAYER_STATS/name#123")
}) {
Text(text = "go to next screen and pass value")
}
}
composable(
"$PLAYER_STATS/{$PLAYER_TAG}",
arguments = listOf(navArgument(PLAYER_TAG) { type = NavType.StringType }),
) {
val viewModel: PlayerStatsScreenViewModel = hiltViewModel()
Text(text = viewModel.userId) // "name#123" is passed in navigate() call but this will display "name"
}
}
}
}
@HiltViewModel
class PlayerStatsScreenViewModel
@Inject
constructor(
savedStateHandle: SavedStateHandle,
) : ViewModel() {
val userId: String = checkNotNull(savedStateHandle[PLAYER_TAG])
// val state = MutableStateFlow(userId)
}
const val HOME = "home"
const val PLAYER_STATS = "playerStats"
const val PLAYER_TAG = "playerTag"