Add favourite button
This commit is contained in:
parent
9b0d0e2bea
commit
6fea30789d
@ -15,7 +15,8 @@ data class PokemonDetails(
|
||||
val id: Int,
|
||||
val name: String,
|
||||
val types: List<Type>,
|
||||
@SerializedName("sprites") val sprites: Sprites
|
||||
@SerializedName("sprites") val sprites: Sprites,
|
||||
var isFavorite: Boolean = false
|
||||
)
|
||||
|
||||
data class Type(
|
||||
|
@ -39,4 +39,14 @@ class PokeSearchViewModel : ViewModel() {
|
||||
val parts = url.split("/")
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -80,7 +80,9 @@ fun PokeSearch(pokeSearchViewModel: PokeSearchViewModel) {
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
items(items = results, key = { pokemon -> pokemon.id }) { pokemon ->
|
||||
PokemonCard(pokemon)
|
||||
PokemonCard(pokemon, toggleFavorite = { pokemonId ->
|
||||
pokeSearchViewModel.toggleFavorite(pokemonId)
|
||||
})
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@ -92,7 +94,7 @@ fun PokeSearch(pokeSearchViewModel: PokeSearchViewModel) {
|
||||
|
||||
|
||||
@Composable
|
||||
fun PokemonCard(pokemon: PokemonDetails) {
|
||||
fun PokemonCard(pokemon: PokemonDetails, toggleFavorite: (Int) -> Unit) {
|
||||
var isFavourite by remember { mutableStateOf(false) }
|
||||
Card(
|
||||
shape = MaterialTheme.shapes.medium,
|
||||
@ -128,7 +130,7 @@ fun PokemonCard(pokemon: PokemonDetails) {
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
IconButton(
|
||||
onClick = { isFavourite = !isFavourite },
|
||||
onClick = { toggleFavorite(pokemon.id) },
|
||||
modifier = Modifier.wrapContentSize()
|
||||
.layout { measurable, constraints ->
|
||||
if (constraints.maxHeight == Constraints.Infinity) {
|
||||
@ -142,7 +144,7 @@ fun PokemonCard(pokemon: PokemonDetails) {
|
||||
}
|
||||
) {
|
||||
Icon(
|
||||
imageVector = if (isFavourite) Icons.Filled.Favorite else Icons.Outlined.FavoriteBorder,
|
||||
imageVector = if (pokemon.isFavorite) Icons.Filled.Favorite else Icons.Outlined.FavoriteBorder,
|
||||
contentDescription = "Favourite"
|
||||
)
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user