Jetpack Compose

Oct 11 2022 Kotlin 1.7.10, Android 13, Android Studio Chipmunk

Part 1: Jetpack Compose Basics

4. Add State to Composables

Episode complete

Play next episode

Next
Save for later
About this episode
See versions

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 3. Use Basic Compose Building Blocks Next episode: 5. Decouple Composables

The student materials have been reviewed and are updated as of September 2022.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.

Demo

So far you’ve been getting to know the Jetpack Compose framework, and it’s been going great! :]

private val _genresState = MutableLiveData(emptyList<Genre>())
override fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(savedInstanceState)
  setContent { AddBookContent() }

  loadGenres()
}

private fun loadGenres() {
  lifecycleScope.launch {
    _genresState.value = repository.getGenres()
  }
}
val genres = _genresState.value ?: emptyList()
val isGenresPickerOpen = remember { mutableStateOf(false) }
val bookNameState = remember { mutableStateOf("") }
val bookDescriptionState = remember { mutableStateOf("") }
val selectedGenreName =
  genres.firstOrNull { it.id == _addBookState.value?.genreId }?.name ?: "None"
OutlinedTextField(
value = bookNameState.value, // new
onValueChange = { newValue -> // new
  bookNameState.value = newValue 
  _addBookState.value = _addBookState.value?.copy(name = newValue)
},
label = { Text(text = stringResource(id = R.string.book_title_hint)) })

OutlinedTextField(
value = bookDescriptionState.value, // new
onValueChange = { newValue -> // new
  bookDescriptionState.value = newValue
  _addBookState.value =_addBookState.value?.copy(description = newValue)
},
label = { Text(text = stringResource(id = R.string.book_description_hint)) })
Row {
  TextButton(
    onClick = { isGenresPickerOpen.value = true }, // new
    content = { Text(text = stringResource(id =  R.string.genre_select)) })

  DropdownMenu(
    expanded = isGenresPickerOpen.value, // new
    onDismissRequest = { isGenresPickerOpen.value = false }) { // new

    for (genre in genres) { // new
      DropdownMenuItem(onClick = {
        _addBookState.value = _addBookState.value?.copy(genreId = genre.id)
        isGenresPickerOpen.value = false
      }) {
        Text(text = genre.name)
      }
    }
  }
}
Row(verticalAlignment = Alignment.CenterVertically) { // alignment
  ...

  Text(text = selectedGenreName) // text element
}