DEV Community

Bernat Borrás Paronella for Adevinta Spain

Posted on

9 2

Jetpack Compose - Alert Dialogs

Material Aalert Dialog

The code presented in this article is using compose rc01

Jetpack Compose brings us with a cool new UI toolkit, but some things are completely different from how we are used to it, one of these cases is AlertDialog a common component on any application.

Steps to display an AlertDialog on compose:

  • Create a state as a flag to check if we need to show the dialog or not.
var showDialog by remember { mutableStateOf(false) }
Enter fullscreen mode Exit fullscreen mode

You may need to import:
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue

Basic AlertDialog:

if (showDialog) {
    AlertDialog(
        onDismissRequest = {  },
        title = {  },
        text = { },
        confirmButton = { },
        dismissButton = { },
    )
}
Enter fullscreen mode Exit fullscreen mode

Let's see what's each param of AlertDialog composable method:

    onDismissRequest = {  },
Enter fullscreen mode Exit fullscreen mode

Will be called when clicking outside of a dialog, here we must set showDialog to false to remove it from our stack.

    title = {  },
    text = {  },
Enter fullscreen mode Exit fullscreen mode

Add a Text to show a title and message of our AlertDialog

    confirmButton = { },
    dismissButton = { },
Enter fullscreen mode Exit fullscreen mode

Define a Button or TextButton and its Text to get actions like "Accept" or "Cancel"

When click on confirm or button we must set our showDialog to false also, to avoid showing the dialog on the next recomposition.

    onDismissRequest = { showDialog = false },
    confirmButton = { showDialog = false },
    dismissButton = { showDialog = false },
Enter fullscreen mode Exit fullscreen mode

Other dialogs

What if we want to display custom content, like a list of items to select one?

    text = { 
       LazyColumn {
          items(...) { item -> Text(text = item) }
       }
    },
Enter fullscreen mode Exit fullscreen mode

Use the text field of AlertDialog to display any content that is needed and handle the dialog in the same way of buttons: showDialog = false.

Hope you enjoyed the article!

Alt Text

Sentry mobile image

Mobile Vitals: A first step to Faster Apps

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read the guide

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more