One Off the Slack: How Big Can I Get?

Rafsanjani Aziz asked an all-too-common question, albeit this time in a Compose environment:

How do I obtain the screen size in compose?

Selcuk Bulca offered an answer that truly answers the question:

You can use ConfigurationAmbient to get screen width and height dp values, then convert them to pixels with DensityAmbient

val screenWidthDp = ConfigurationAmbient.current.screenWidthDp
        val screenHeightDp = ConfigurationAmbient.current.screenHeightDp
        val (screenWidthPx, screenHeightPx) = with(DensityAmbient.current) {
            screenWidthDp.dp.toPx() to screenHeightDp.dp.toPx()

However, in truth, the question itself is a problem.

As Google’s Jim Sproch put it:

The composable should be reacting to the immediate space available, not to the number of pixels that the device happens to have; otherwise your composable will likely behave wrong when placed in a smaller context.

While mobile developers are used to thinking of “the screen” as being where they can render a UI, in reality, that has not been true in years. Split-screen and multi-window support was added in Android 8.0, and in either case, your UI space is less than the screen size.

Plus, as Jim pointed out:

Using the configuration ambient will tie yourself to Android and will make your composable unsuitable for things like unit testing (not to mention being able to reuse the composable in other contexts, like Desktop).

Laurent Bernabé suggested WithConstraints:

WithConstraints {
  val width = constraints.maxWidth
  val height = constraints.maxHeight

This height and width will be what space is available to your UI, taking into account desktop or multi-window windows. It is usually a more relevant size value to your app than is the literal screen size.

Read the original thread in the kotlinlang Slack workspace. Not a member? Join that Slack workspace here!