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

Viewed 77

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. But it'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)
  ...
}
  1. 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 3'th variant because it seems more flexible and allows us to avoid returning to xmls. But it will require efforts to support it.

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

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
Related