Jetpack Compose Navigation:How to pass an array as an argument?

Viewed 1943

I have a filter dialog that shows filter options :

enter image description here

When I click on "Parent Platform" section I'm navigating to the PlatformsScreen with two arguments. Argument one is parent which is int and the second is platforms which is an array of int :

sealed class Screen(val route: String, val arguments: List<NamedNavArgument>) {

    object PlatformScreen : Screen(PLATFORM_ROUTE,arguments = 
        listOf(navArgument("parent", builder = {type = NavType.IntType}),
        navArgument("platforms",builder = {type = NavType.IntArrayType})))
}


// click action
@Composable
fun FilterDialog(
    modifier: Modifier = Modifier,
    viewModel: FilterViewModel,
    navigateToPlatformScreen: (Int,Array<Int?>) -> Unit
) {
 val filterState by viewModel.filterState.collectAsState()
 Row(//other stuff
       .clickable {
                    navigateToPlatformScreen(filterState.parentPlatform?.id ?: -1,
                    filterState.platforms?.map { it?.id }?.toTypedArray() ?: arrayOf(-1))
                }
)
  //here is my filter bottom sheet
   bottomSheet(route = FILTER_ROUTE) {
        FilterDialog(viewModel = viewModel,
            navigateToPlatformScreen = { parentId,platforms ->
                navController.navigate("${Screen.PlatformScreen.route}?parent=${parentId}&platforms=${platforms}")
            })
    }

    //platforms screen
    bottomSheet(route = Screen.PlatformScreen.route+"?parent={parent}&platforms={platforms}",arguments = Screen.PlatformScreen.arguments) { backstackEntry ->
        val parent = backstackEntry.arguments?.getInt("parent")
        val platforms = backstackEntry.arguments?.getIntArray("platforms")
        PlatformScreen(parent = parent,platforms = platforms)
    }  

And as the last part, here is my FilterViewModel that holds my parentId and platforms array :

class FilterViewModel : ViewModel() {

    private val _selectedParentPlatform = MutableStateFlow<ParentPlatform?>(ParentPlatform())

    private val _filterState = MutableStateFlow(FilterState())

    val filterState:StateFlow<FilterState> get() = _filterState

    init {
        viewModelScope.launch {
           _selectedParentPlatform.mapLatest {
               FilterState(
                   parentPlatform = it,
                   platforms = it?.platforms
               )
           }
                .catch { cause ->

                }
                .collectLatest {
                    _filterState.value = it
                }
        }
    }
}

I have no problem with parent argument. I can pass it with no problem however the array type causing a crash with the following error: java.lang.UnsupportedOperationException: Arrays don't support default values.

0 Answers
Related