onConsumedWindowInsetsChanged

Functions summary

Modifier
Modifier.onConsumedWindowInsetsChanged(
    block: (consumedWindowInsets: WindowInsets) -> Unit
)

Calls block with the WindowInsets that have been consumed, either by consumeWindowInsets or one of the padding Modifiers, such as imePadding.

Cmn

Functions

Modifier.onConsumedWindowInsetsChanged

fun Modifier.onConsumedWindowInsetsChanged(
    block: (consumedWindowInsets: WindowInsets) -> Unit
): Modifier

Calls block with the WindowInsets that have been consumed, either by consumeWindowInsets or one of the padding Modifiers, such as imePadding.

block can be called before or during measurement and layout. It should not be used to trigger changes to composition because composition will only be applied on the following frame, leading to the UI lagging WindowInsets by a frame.

import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.MutableWindowInsets
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.exclude
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.onConsumedWindowInsetsChanged
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeContent
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.core.view.WindowCompat

class SampleActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        super.onCreate(savedInstanceState)
        setContent {
            val remainingInsets = remember { MutableWindowInsets() }
            val safeContent = WindowInsets.safeContent
            Box(
                Modifier.navigationBarsPadding().onConsumedWindowInsetsChanged {
                    consumedWindowInsets ->
                    remainingInsets.insets = safeContent.exclude(consumedWindowInsets)
                }
            ) {
                // padding can be used without recomposition when insets change.
                val padding = remainingInsets.asPaddingValues()
                Box(Modifier.padding(padding))
            }
        }
    }
}