28
Showing Dialogs with Jetpack Compose

Understanding how Jetpack Compose treats state and recomposition are crucial to effectively using Compose. The ramifications of state changes in your code being the trigger for UI updates extend throughout the framework. A great example of this is how Compose handles dialogs.

When you want to display a dialog in the framework UI toolkit, you use a class like AlertDialog or DatePickerDialog – ideally, wrapped in a DialogFragment. To display one of these dialogs, you call the appropriate show function. The dialog then does whatever it wants to do and dismisses itself. If there is a result it needs to send back to whatever component summoned it, it needs to safely transfer the data back to that location – often with a fair amount of orchestration.

In Compose, dialogs follow the same rule of declarative UIs that you have seen before: If you say that a dialog should be shown, it will be shown. You are in control of when the dialog disappears – the dialog can request that it be dismissed, but the call site gets the final say.

Because the state of whether the dialog is visible is known by the composable that hosts the dialog, there is no need to wrap the dialog in another container to manage its lifecycle. And because the dialog is directly managed by another composable, transferring data between the two is as simple as declaring a lambda expression to serve as a callback – no need to set up a finicky line of communication between two components.

In Coda Pizza, you will use a dialog to ask your users where they would like a topping to be placed on their pizza. The finished dialog will look like Figure 28.1, and it will appear any time the user selects a topping from the list.

Figure 28.1  The final dialog

The final dialog
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.205.3