iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📱

How to Resolve Compose ModalBottomSheet Snackbar Hiding Issues Using Dialog Overlay

に公開

Verification Environment: Compose BOM 2024.12.01 / Material3 1.3.1 / Android 15-16 (Pixel 8, Sony Xperia 1 VI, Samsung Galaxy S25 Ultra)

What is happening

A QA report indicated that the Snackbar for a mute operation was not appearing in production. Upon investigation, I found that the Snackbar was hidden behind the sheet when ModalBottomSheet was open.

Applying Modifier.zIndex() was ineffective. Even using the snackbarHost parameter of Scaffold did not help.

This has been reported on Google's Issue Tracker, but as of December 2025, the status is "Not started" (check Issue #377543106 for the latest status).

https://issuetracker.google.com/issues/377543106

Incidentally, the same issue has been reported in Flutter, so it seems to be an inherent challenge with modal UIs regardless of the platform.

Why it happens

The cause lies in the internal implementation of ModalBottomSheet.

M3's ModalBottomSheet uses the Compose Dialog composable internally. Dialog creates a new Android Window (an OS-level rendering layer). In other words, when the sheet is displayed, a separate window from the app's main window is generated on top.

[Window 1] Activity main window
  └── Scaffold
       ├── SnackbarHost  ← Located here
       └── Content

[Window 2] ModalBottomSheet Dialog window  ← This one is on top
  └── Sheet content

Because the SnackbarHost is in the main window (Window 1), it is hidden underneath the ModalBottomSheet (Window 2), which is in a different window. Modifier.zIndex() does not affect different windows.

Common workarounds and their limits

1. Place SnackbarHost inside the ModalBottomSheet

ModalBottomSheet(onDismissRequest = { ... }) {
    Scaffold(
        snackbarHost = { SnackbarHost(snackbarHostState) }
    ) {
        // Sheet content
    }
}

This works, but the Snackbar only appears within the sheet. Furthermore, you have to inject SnackbarHost every time you open a sheet. If there are 10 modals in the app, you end up writing it in 10 places...

2. Use Toast

Give up on Snackbar and use Toast instead. There is zero design freedom, and it does not align with Material Design guidelines.

3. Use Material 2's ModalBottomSheetLayout

M2's ModalBottomSheetLayout does not create a separate window and renders within the same Composition, so this problem does not occur. However, staying on M2 for this reason is counterproductive.

Which one to choose?

Method Snackbar Position Maintenance Load Action Button Limitations
SnackbarHost inside Sheet Inside sheet only High (per modal) Supported Disappears when sheet closes
Fallback to Toast System Toast Low Not supported Zero design freedom
Stay on M2 Normal Low Supported Cannot migrate to M3
Dialog overlay (described below) Screen foreground Low (one place) Not supported Beware of OEM differences

If you don't need an action-enabled Snackbar and want to use it consistently throughout the app, the Dialog overlay was the easiest approach.

Solution: Dialog overlay

Change your perspective and display the Snackbar using a separate Dialog.

Android Dialogs created later appear on top. Therefore, if you create a Dialog for the Snackbar after the ModalBottomSheet's Dialog, the Snackbar will appear on top.

[Window 1] Activity
[Window 2] ModalBottomSheet
[Window 3] Snackbar Dialog  ← Foreground

The key is to ensure that Window 3 does not consume any touches.

Complete code

@Composable
fun SnackbarOverlayDialog(
    snackbarHostState: SnackbarHostState,
) {
    // Do not show the dialog when there is no Snackbar
    if (snackbarHostState.currentSnackbarData == null) return

    Dialog(
        onDismissRequest = { },
        properties = DialogProperties(
            usePlatformDefaultWidth = false,  // Expand Dialog to full screen width
            dismissOnBackPress = false,
            dismissOnClickOutside = false,
            decorFitsSystemWindows = false,   // Render including system bar areas
        )
    ) {
        // DialogWindowProvider: Get a reference to the Android Window that the Compose Dialog holds internally
        val dialogWindow = (LocalView.current.parent as? DialogWindowProvider)?.window
        SideEffect {
            dialogWindow?.apply {
                setDimAmount(0f)
                clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
                addFlags(
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                        WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
                )
            }
        }

        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(bottom = 24.dp),
            contentAlignment = Alignment.BottomCenter,
        ) {
            SnackbarHost(hostState = snackbarHostState)
        }
    }
}

How to use

Leave the Scaffold's snackbarHost empty, and call SnackbarOverlayDialog inside the content block.

val snackbarHostState = remember { SnackbarHostState() }

Scaffold { innerPadding ->
    // Main content
    MainContent(modifier = Modifier.padding(innerPadding))

    // Snackbar overlay (placed after ModalBottomSheet)
    SnackbarOverlayDialog(snackbarHostState = snackbarHostState)
}

:::

Why FLAG_NOT_FOCUSABLE is not enough

This was the tricky part.

At first, I thought FLAG_NOT_FOCUSABLE would be enough. Since FLAG_NOT_FOCUSABLE implicitly includes FLAG_NOT_TOUCH_MODAL, I expected touches to pass through... but they don't.

The reason is as follows:

  • FLAG_NOT_TOUCH_MODAL only passes through touches to the outside of the Window.
  • With usePlatformDefaultWidth = false + fillMaxSize(), the Dialog covers the entire screen.
  • Since the entire screen is "inside" the window, all touches are absorbed by the Dialog.

By adding FLAG_NOT_TOUCHABLE, the window itself stops receiving touch events entirely, causing all touches to pass through to the window below.

// ❌ Touches will not pass through with this alone
setFlags(
    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
)

// ✅ FLAG_NOT_TOUCHABLE is also required, and remove FLAG_DIM_BEHIND
clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
addFlags(
    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
        WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
)

Points to note

I have listed the problems I encountered in production in order of priority.

[Critical] FLAG_DIM_BEHIND blocks touches on some OEMs

Compose Dialog sets FLAG_DIM_BEHIND by default. On devices like Pixel, setDimAmount(0f) is sufficient, but on some OEMs like Sony Xperia, the dim surface intercepts touches independently of FLAG_NOT_TOUCHABLE.

If you don't explicitly call clearFlags(FLAG_DIM_BEHIND), buttons and sheets under the Snackbar will become completely untappable. I actually encountered this issue in production.

Also, the reason I use SideEffect instead of LaunchedEffect is to ensure the flags are applied correctly at every recomposition. There are cases where Compose resets window flags on some devices.

[Consideration required] Snackbar action buttons are untappable

Since FLAG_NOT_TOUCHABLE is set, the Snackbar itself cannot be tapped. Be careful if you want to use a Snackbar with an "Undo" button.

Possible countermeasures:

  • Remove FLAG_NOT_TOUCHABLE while the Snackbar is displayed and manually forward touches outside the Snackbar to the window below.
  • Or, use a different approach for screens that require Snackbars with actions.

At the moment, I don't have any use cases requiring action-enabled Snackbars, so I accept this limitation.

[Minor] Conflict in display order

If a new ModalBottomSheet is opened while a Snackbar is being displayed, that Dialog might appear above the Snackbar Dialog. However, since a Snackbar usually disappears in 3 seconds, it hasn't been a practical problem.

Sample App

I have prepared a demo app where you can switch between Before (standard Scaffold SnackbarHost) and After (Dialog overlay).

Demo

https://github.com/user/zenn-article/tree/main/articles/compose-snackbar-above-modalbottomsheet

MainActivity.kt (folded)
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MaterialTheme {
                SnackbarDemo()
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SnackbarDemo() {
    var useOverlay by remember { mutableStateOf(false) }
    var showSheet by remember { mutableStateOf(false) }
    val snackbarHostState = remember { SnackbarHostState() }
    val scope = rememberCoroutineScope()

    Scaffold(
        snackbarHost = {
            // Before: Standard SnackbarHost (hidden behind ModalBottomSheet)
            if (!useOverlay) {
                SnackbarHost(hostState = snackbarHostState)
            }
        },
    ) { innerPadding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(innerPadding)
                .padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(16.dp),
        ) {
            Text(
                text = if (useOverlay) "After: Dialog Overlay" else "Before: Scaffold SnackbarHost",
                style = MaterialTheme.typography.headlineSmall,
            )

            Row(verticalAlignment = Alignment.CenterVertically) {
                Text("Use Dialog Overlay")
                Spacer(modifier = Modifier.width(8.dp))
                Switch(checked = useOverlay, onCheckedChange = { useOverlay = it })
            }

            Button(onClick = { showSheet = true }) {
                Text("Show BottomSheet")
            }

            Button(onClick = {
                scope.launch {
                    snackbarHostState.showSnackbar("Hello from Snackbar!")
                }
            }) {
                Text("Show Snackbar")
            }
        }

        // After: Dialog overlay (displayed above ModalBottomSheet)
        if (useOverlay) {
            SnackbarOverlayDialog(snackbarHostState = snackbarHostState)
        }
    }

    if (showSheet) {
        ModalBottomSheet(onDismissRequest = { showSheet = false }) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(24.dp),
            ) {
                Text(
                    text = "ModalBottomSheet",
                    style = MaterialTheme.typography.headlineSmall,
                )
                Spacer(modifier = Modifier.height(8.dp))
                Text("Try displaying the Snackbar in this state")
                Spacer(modifier = Modifier.height(16.dp))
                Button(onClick = {
                    scope.launch {
                        snackbarHostState.showSnackbar("Snackbar while sheet is open!")
                    }
                }) {
                    Text("Show Snackbar")
                }
                Spacer(modifier = Modifier.height(48.dp))
            }
        }
    }
}

@Composable
fun SnackbarOverlayDialog(
    snackbarHostState: SnackbarHostState,
) {
    if (snackbarHostState.currentSnackbarData == null) return

    Dialog(
        onDismissRequest = { },
        properties = DialogProperties(
            usePlatformDefaultWidth = false,
            dismissOnBackPress = false,
            dismissOnClickOutside = false,
            decorFitsSystemWindows = false,
        )
    ) {
        val dialogWindow = (LocalView.current.parent as? DialogWindowProvider)?.window
        SideEffect {
            dialogWindow?.apply {
                setDimAmount(0f)
                clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
                addFlags(
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                        WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
                )
            }
        }

        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(bottom = 24.dp),
            contentAlignment = Alignment.BottomCenter,
        ) {
            SnackbarHost(hostState = snackbarHostState)
        }
    }
}

Please let me know if there is a better way

This Dialog overlay method is just a workaround, and I don't believe it's the optimal solution. There is the limitation that action buttons cannot be tapped due to FLAG_NOT_TOUCHABLE, and frankly, it's hard to call it a clean solution considering the behavioral differences among OEMs.

If you are having the same problem and have found a better approach, please let me know in the comments.

References

GitHubで編集を提案

Discussion