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:
dimens.xml and get the values directly in the compose functions calling dimensionResource().dimens.xml in a Kotlin class. For example:
class AppDimensions {
val paddingSmall: Dp
@Composable
get() = dimensionResource(R.dimen.padding_small)
...
}
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With