Jetpack Compose

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

Part 1: Jetpack Compose Basics

04. Add State to Composables

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

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

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Notes: 04. Add State to 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.

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
}