Search code examples
kotlinandroid-jetpack-composeandroid-jetpack-compose-material3

Mutable state of empty List


I would like do a mutableStateOf for my umpty list because I don't have items to put in yet.

@Composable
fun AppScaffold(){
    val navigationController = rememberNavController()
    var type by remember { mutableStateOf()}
    Scaffold(
        topBar = { AppBarTop() },
        containerColor = MaterialTheme.colorScheme.surface
    ){paddingValues ->
        NavHost(
            navController = navigationController,
            startDestination = Screens.POKEDEX.name,
            modifier = Modifier.padding(paddingValues)
        ){
            composable(route = Screens.POKEDEX.name){
                AppContent(onClick = {
                    type = it
                    navigationController.navigate(route = Screens.DETAILS.name)
                })
            }
            composable(route = Screens.DETAILS.name){
                DetailView(type = type)
            }
        }
    }
}

This is my main Function. I receive a Types from my AppContent View.

My data class is :

data class PokedexResults(
    val list: List<Types>
)

data class Types(
    val id: Int,
    val name: String,
    val image: String,
    val stats: PokemonStats,
    val apiTypes: List<apiTypes>
)

data class PokemonStats(
    val HP: Int,
    val attack: Int,
    val defense: Int,
    val special_attack: Int,
    val special_defense: Int,
)

data class apiTypes(
    val name: String,
    val image: String
)

I tried this var type by remember { mutableStateOf(PokedexResults().list)} error

I tried to have a mutable state of because i need to change the type when another is received from my AppContent View


Solution

  • To create an empty List in Kotlin, you can use the emptyList() or listOf() function:

    var myList by remember { mutableStateOf(emptyList())}  // create empty List
    

    In your case, you could use

    var type by remember { mutableStateOf(PokedexResults(emptyList()).list)}
    

    You can also consider to provide a default value for the list parameter of the PokedexResults data class like this:

    data class PokedexResults(
        val list: List<Types> = emptyList()
    )
    

    Then, when no list is provided, it will automatically initialize the list to an empty list.

    Edit:
    Make sure to adapt your code to properly handle cases where the List is empty. Using the first() function on an empty List will throw an NoSuchElementException.