Tech Sheets

How to show Snackbar in Jetpack Compose

最終更新日:2024-07-10

To display a Snackbar in Jetpack Compose, use Scaffold and snackbarHost .

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainScreen() {
  val hostState = remember { SnackbarHostState() }
  val scope = rememberCoroutineScope()

  Scaffold(
    snackbarHost = { SnackbarHost(hostState) }
  ) { paddingValues ->
    Column(modifier = Modifier.padding(paddingValues)) {
      Button(onClick = {
        scope.launch {
          hostState.showSnackbar("Message")
        }
      }) {
        Text("Snack bar")
      }
    }
  }
}

To show the snackbar, call snackbarHostState.showSnackbar() . Since it is a suspend fun , it must be executed in a coroutine scope.

Button(onClick = {
  scope.launch {
    hostState.showSnackbar("Message")
  }
}) {
  Text("Snack bar")
}

The preview will look like this:

一覧に戻る