Add favourite button

This commit is contained in:
Joren 2024-04-29 21:26:35 +02:00
parent 9b0d0e2bea
commit 6fea30789d
Signed by untrusted user who does not match committer: Joren
GPG Key ID: 280E33DFBC0F1B55
3 changed files with 18 additions and 5 deletions

View File

@ -15,7 +15,8 @@ data class PokemonDetails(
val id: Int, val id: Int,
val name: String, val name: String,
val types: List<Type>, val types: List<Type>,
@SerializedName("sprites") val sprites: Sprites @SerializedName("sprites") val sprites: Sprites,
var isFavorite: Boolean = false
) )
data class Type( data class Type(

View File

@ -39,4 +39,14 @@ class PokeSearchViewModel : ViewModel() {
val parts = url.split("/") val parts = url.split("/")
return parts[parts.size - 2].toInt() return parts[parts.size - 2].toInt()
} }
fun toggleFavorite(pokemonId: Int) {
_pokemonDetails.value = _pokemonDetails.value?.map { pokemon ->
if (pokemon.id == pokemonId) {
pokemon.copy(isFavorite = !pokemon.isFavorite)
} else {
pokemon
}
}
}
} }

View File

@ -80,7 +80,9 @@ fun PokeSearch(pokeSearchViewModel: PokeSearchViewModel) {
horizontalArrangement = Arrangement.spacedBy(8.dp) horizontalArrangement = Arrangement.spacedBy(8.dp)
) { ) {
items(items = results, key = { pokemon -> pokemon.id }) { pokemon -> items(items = results, key = { pokemon -> pokemon.id }) { pokemon ->
PokemonCard(pokemon) PokemonCard(pokemon, toggleFavorite = { pokemonId ->
pokeSearchViewModel.toggleFavorite(pokemonId)
})
} }
} }
} else { } else {
@ -92,7 +94,7 @@ fun PokeSearch(pokeSearchViewModel: PokeSearchViewModel) {
@Composable @Composable
fun PokemonCard(pokemon: PokemonDetails) { fun PokemonCard(pokemon: PokemonDetails, toggleFavorite: (Int) -> Unit) {
var isFavourite by remember { mutableStateOf(false) } var isFavourite by remember { mutableStateOf(false) }
Card( Card(
shape = MaterialTheme.shapes.medium, shape = MaterialTheme.shapes.medium,
@ -128,7 +130,7 @@ fun PokemonCard(pokemon: PokemonDetails) {
overflow = TextOverflow.Ellipsis overflow = TextOverflow.Ellipsis
) )
IconButton( IconButton(
onClick = { isFavourite = !isFavourite }, onClick = { toggleFavorite(pokemon.id) },
modifier = Modifier.wrapContentSize() modifier = Modifier.wrapContentSize()
.layout { measurable, constraints -> .layout { measurable, constraints ->
if (constraints.maxHeight == Constraints.Infinity) { if (constraints.maxHeight == Constraints.Infinity) {
@ -142,7 +144,7 @@ fun PokemonCard(pokemon: PokemonDetails) {
} }
) { ) {
Icon( Icon(
imageVector = if (isFavourite) Icons.Filled.Favorite else Icons.Outlined.FavoriteBorder, imageVector = if (pokemon.isFavorite) Icons.Filled.Favorite else Icons.Outlined.FavoriteBorder,
contentDescription = "Favourite" contentDescription = "Favourite"
) )
} }