Issue
There's Surface composable in Jetpack Compose which represents a material surface. A surface allows you to setup things like background color or border but it seems that the same might be done using modifiers. When should I use the Surface composable and what the benefits it gives me?
Solution
Surface composable makes the code easier as well as explicitly indicates that the code uses a material surface. Let's see an example:
Surface(
color = MaterialTheme.colors.primarySurface,
border = BorderStroke(1.dp, MaterialTheme.colors.secondary),
shape = RoundedCornerShape(8.dp),
elevation = 8.dp
) {
Text(
text = "example",
modifier = Modifier.padding(8.dp)
)
}
and the result:
The same result can be achieved without Surface:
val shape = RoundedCornerShape(8.dp)
val shadowElevationPx = with(LocalDensity.current) { 2.dp.toPx() }
val backgroundColor = MaterialTheme.colors.primarySurface
Text(
text = "example",
color = contentColorFor(backgroundColor),
modifier = Modifier
.graphicsLayer(shape = shape, shadowElevation = shadowElevationPx)
.background(backgroundColor, shape)
.border(1.dp, MaterialTheme.colors.secondary, shape)
.padding(8.dp)
)
but it has a few drawbacks:
- The modifiers chain is pretty big and it isn't obvious that it implements a material surface
- I have to declare a variable for the shape and pass it into three different modifiers
- It uses contentColorFor to figure out the content color while Surface does it under the hood. As a result the
backgroundColor
is used in two places as well. - I have to calculate the elevation in pixels
Surface
adjusts colors for elevation (in case of dark theme) according to the material design. If you want the same behavior, it should be handled manually.
For the full list of Surface features it's better to take a look at the documentation.
Answered By - Valeriy Katkov
Answer Checked By - Cary Denson (JavaFixing Admin)