Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best practice using dp and sp dimensions in Jetpack Compose?

I would like to understand how is better to use dp and sp values in the Compose project. I checked several open source Compose projects and most of them are hardcoding the dimensions. That's definitely not a way to support flexibility and different screen sizes. I see a few ways for now:

  1. Using the old way with dimens.xml and get the values directly in the compose functions calling dimensionResource().
  2. Having references to the values of dimens.xml in a Kotlin class. For example:
    class AppDimensions {
        val paddingSmall: Dp
        @Composable
        get() = dimensionResource(R.dimen.padding_small)
    ...
    }
    
  3. Not to use the dimens.xml and implement your own logic for different screen sizes. For example:
    class AppDimensions {
        val paddingSmall = when(screenSize) {
            Compact -> 10.dp
            Medium -> 16.dp
            Expanded -> 20.dp
            else -> 10.dp
        }
        ...
    }
    

I like the third variant because it seems more flexible and allows us to avoid returning to XML. But it will require effort to support it.

But, maybe, can we use it in some more convenient way?

like image 845
sergpetrov Avatar asked Dec 18 '25 12:12

sergpetrov


1 Answers

I am using this way in compose;

val LocalDim = compositionLocalOf { Dimensions() }

data class Dimensions(
    val default: Dp = 0.dp,
    val spaceXXSmall: Dp = 2.dp,
    val spaceExtraSmall: Dp = 4.dp,
    val spaceSmall: Dp = 8.dp,
    val spaceMedium: Dp = 16.dp,
    val spaceLarge: Dp = 32.dp,
    val spaceExtraLarge: Dp = 64.dp,
    val spaceXXLarge: Dp = 128.dp,
    val spaceXXXLarge: Dp = 256.dp
}

for use;

val dimensions = LocalDim.current
like image 105
commandiron Avatar answered Dec 21 '25 02:12

commandiron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!