Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 104 ยท Building a Real UI

Scaffold, App Bars, Dialogs and Snackbars

Build the frame of a Compose screen: Scaffold slots, TopAppBar, floating action button, SnackbarHost, AlertDialog and bottom sheets, plus how to handle one-off UI messages.

Most screens share the same frame: a bar at the top with a title, perhaps a button floating in a corner, a place where short messages appear, and content that must not slide underneath any of them. You could position all of that by hand with Box and Column, but every screen would get the spacing slightly different and you would have to handle system bars yourself. Material 3 gives you Scaffold, a layout that owns the frame and hands your content the right padding.

This lesson covers the Scaffold slots, the app bars, the snackbar host, dialogs and bottom sheets, and then looks at a question that trips up many beginners: how should a ViewModel say "show this message once"? The Compose code here is read-only (it needs the Android SDK and a device); the TryIt blocks are stand-ins that model the layout rules and the message queue in plain Kotlin on the server. Forms and buttons were covered in Buttons, Text Fields and Forms.

Scaffold and its slots

Scaffold is a layout with named slots. Each slot is a composable lambda, and each one is optional:

Kotlin
// read-only example: needs the Android SDK and Compose
@Composable
fun NotesScreen(notes: List<String>, onAdd: () -> Unit) {
    Scaffold(
        topBar = { TopAppBar(title = { Text("Notes") }) },
        floatingActionButton = {
            FloatingActionButton(onClick = onAdd) {
                Icon(Icons.Default.Add, contentDescription = "Add note")
            }
        },
        snackbarHost = { SnackbarHost(hostState = snackbarHostState) },
    ) { innerPadding ->
        LazyColumn(contentPadding = innerPadding) {
            items(notes) { note -> ListItem(headlineContent = { Text(note) }) }
        }
    }
}

The last lambda is the content, and it receives innerPadding: a PaddingValues that describes how much room the bars take. You must apply it, as contentPadding on a scrolling list or as Modifier.padding(innerPadding) on a plain container. If you ignore it, the first row of your list hides behind the top bar, and the compiler warns you about it.

Other slots include bottomBar (for a NavigationBar or BottomAppBar) and containerColor. The floating action button is placed at the end of the bottom edge by default, above the bottom bar if there is one.

flowchart TB
    subgraph S["Scaffold"]
        direction TB
        T["topBar"]
        C["content<br/>(receives innerPadding)"]
        B["bottomBar"]
    end
    F["floatingActionButton"]
    N["snackbarHost"]
    C -.-> F
    C -.-> N

The frame: top bar and bottom bar take space, the content gets the rest; the FAB and snackbar float above the content.

The idea behind the padding is simple subtraction. The stand-in below models a screen of a given height: bars subtract their height, and what remains is the content area. This is what innerPadding tells you in the real framework.

Kotlin How Scaffold computes innerPadding (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

App bars

Material 3 has four top app bars: TopAppBar (small), CenterAlignedTopAppBar, MediumTopAppBar and LargeTopAppBar. The medium and large bars collapse as the list scrolls. To connect the scrolling behavior to the bar, create a TopAppBarScrollBehavior and attach it in two places:

Kotlin
// read-only example
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsScreen(onBack: () -> Unit) {
    val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
    Scaffold(
        modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
        topBar = {
            LargeTopAppBar(
                title = { Text("Settings") },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
                    }
                },
                actions = {
                    IconButton(onClick = { /* search */ }) {
                        Icon(Icons.Default.Search, contentDescription = "Search")
                    }
                },
                scrollBehavior = scrollBehavior,
            )
        },
    ) { innerPadding -> /* list */ }
}

The bar has three regions: navigationIcon (usually Back or a menu), title, and actions (a few icon buttons; extra ones go into a DropdownMenu). Some app bar APIs are marked experimental, which is why @OptIn appears. Every icon button needs a contentDescription so screen readers can announce it.

Snackbars: short messages

A snackbar is a short message at the bottom of the screen, optionally with one action such as "Undo". It is driven by a SnackbarHostState that you create with remember and pass to the snackbarHost slot. You show a message by calling the suspend function showSnackbar, so it needs a coroutine:

Kotlin
// read-only example
val snackbarHostState = remember { SnackbarHostState() }
val scope = rememberCoroutineScope()

Scaffold(snackbarHost = { SnackbarHost(snackbarHostState) }) { padding ->
    Button(
        modifier = Modifier.padding(padding),
        onClick = {
            scope.launch {
                val result = snackbarHostState.showSnackbar(
                    message = "Note deleted",
                    actionLabel = "Undo",
                    duration = SnackbarDuration.Short,
                )
                if (result == SnackbarResult.ActionPerformed) { /* restore the note */ }
            }
        },
    ) { Text("Delete") }
}

showSnackbar suspends until the snackbar is dismissed, then returns a SnackbarResult. Calls are queued: a second message waits for the first. Never call it directly in the composable body (it would run on every recomposition); call it from an event handler or a LaunchedEffect, which you will meet in Side Effects.

Dialogs and bottom sheets

A dialog is just a composable that you include while some state says it should be shown. There is no dialog.show(); the UI is a function of state, so you hold a boolean (or better, the data the dialog needs) and render the dialog when it is set:

Kotlin
// read-only example
var noteToDelete by remember { mutableStateOf<Note?>(null) }

noteToDelete?.let { note ->
    AlertDialog(
        onDismissRequest = { noteToDelete = null },
        title = { Text("Delete note?") },
        text = { Text("\"${note.title}\" will be removed.") },
        confirmButton = {
            TextButton(onClick = { onDelete(note); noteToDelete = null }) { Text("Delete") }
        },
        dismissButton = {
            TextButton(onClick = { noteToDelete = null }) { Text("Cancel") }
        },
    )
}

onDismissRequest fires when the user taps outside the dialog or presses Back; you decide what that means, usually clearing the state. For a bottom sheet, use ModalBottomSheet the same way: show it while a state is true, and pass onDismissRequest plus an optional sheetState for programmatic hide animations. Use dialogs for decisions that block the flow, and sheets for extra actions or details that the user can swipe away.

One-off messages from the ViewModel

A tricky case is "show a snackbar after saving". If the ViewModel keeps message: String? in its UI state, the message is shown again after rotation, because the state survives while the snackbar does not. A message is an event: it should be consumed once. A common pattern is a Channel exposed as a Flow, which the screen collects in a LaunchedEffect:

Kotlin
// read-only example
class NotesViewModel : ViewModel() {
    private val _events = Channel<UiEvent>(Channel.BUFFERED)
    val events = _events.receiveAsFlow()

    fun delete(note: Note) {
        // ...delete it...
        _events.trySend(UiEvent.ShowMessage("Note deleted"))
    }
}

Each event is delivered to exactly one collector and then it is gone. UI State, Events and MVI-style Modelling looks at the trade-offs of this approach; for now, the stand-in shows the behavior. The queue below holds events until a screen is attached, delivers each once, and shows that a "rotation" does not replay old messages.

Kotlin A one-off event queue (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Compare that with putting the message in state: after a rotation, the new screen would read the same message field and show it again unless something resets it. Both approaches work if you are careful, but the event channel makes the "once" explicit.

Common mistakes

  • Ignoring innerPadding. Content hides behind the bars and edge-to-edge insets are wrong.
  • Nesting a Scaffold inside a Scaffold for every screen of a navigation graph without care, which doubles the bars. Decide where the bars live: one shared bar in the outer scaffold, or one per screen.
  • Calling showSnackbar outside a coroutine or in the composable body.
  • Showing dialogs with an imperative flag that is not saved; a dialog open during rotation disappears unless the state is saved. Use rememberSaveable or keep the data in the ViewModel.
  • Missing contentDescription on icon-only buttons.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is innerPadding in the Scaffold content lambda for?

    The top bar, bottom bar and insets take space. innerPadding describes it, and applying it keeps the first and last items from hiding behind a bar.
  2. 2. Why does SnackbarHostState.showSnackbar need a coroutine?

    showSnackbar suspends until the snackbar disappears and then returns a SnackbarResult, so call it from a coroutine such as one started with rememberCoroutineScope or a LaunchedEffect.
  3. 3. How do you show an AlertDialog in Compose?

    Compose UI is a function of state. A boolean or the data the dialog needs is held in state, and the dialog is part of the composition only while that state is set.
  4. 4. Why is a Channel-based event better than a message field in the UI state for a 'Note saved' snackbar?

    A message is a one-off event. Stored in state it is replayed whenever the screen is recreated unless something clears it; a channel delivers each event to one collector and removes it.

Summary

  • Scaffold provides slots (topBar, bottomBar, floatingActionButton, snackbarHost) and passes innerPadding to the content, which you must apply.
  • Material 3 offers small, center-aligned, medium and large top app bars; collapsing ones need a TopAppBarScrollBehavior connected through nestedScroll.
  • Show snackbars with SnackbarHostState.showSnackbar from a coroutine; calls queue up.
  • Dialogs and sheets are composables that are shown while state says so; onDismissRequest decides what a dismissal means.
  • One-off messages are events, not state; a Channel exposed as a Flow delivers each once.
  • Compose code is read-only here; the TryIts model the padding rule and the event queue.

Next: Animation in Compose