Android compose: Surface can have only one direct measurable child

Viewed 1642

I'm new to Jetpack compose, I have create a composable like this.

  Column(
        Modifier.clickable(onClick = onclick)
            .fillMaxWidth().background(pastelGray)
            .padding(16.dp)
    ) {

        Card(backgroundColor = Color.Cyan) {
   //         Image(asset = vectorResource(id = R.drawable.ic_coupon_back), modifier = Modifier.fillMaxWidth())
            Column(modifier = Modifier.padding(8.dp)) {
                Text(text = coupon.couponTitle, color = Color.Red, fontSize = 20.sp)
                Text(text = coupon.couponSubTitle, color = Color.Black, fontSize = 13.sp)
                Text(text = coupon.couponDateTitle, color = Color.Gray, fontSize = 11.sp)
            }
        }
    }

When I add that commented image I got this error:

Surface can have only one direct measurable child!

I could not find the reason till now.

1 Answers

Because Card() composable used in your code uses Surface under the hood:

@Composable
fun Card(
    modifier: Modifier = Modifier,
    shape: Shape = MaterialTheme.shapes.medium,
    backgroundColor: Color = MaterialTheme.colors.surface,
    contentColor: Color = contentColorFor(backgroundColor),
    border: BorderStroke? = null,
    elevation: Dp = 1.dp,
    content: @Composable () -> Unit
) {
    Surface(
        modifier = modifier,
        shape = shape,
        color = backgroundColor,
        contentColor = contentColor,
        elevation = elevation,
        border = border,
        content = content
    )
}

source: Official Card Implementation code

And Surface is a kind like ScrollView doesn't accept more than one direct child. So you need to wrap your code inside Card() into a single parent that is a direct child of Card or in other words direct child of Surface, example:

Card(backgroundColor = Color.Cyan) {
     CardContent()
}

private fun CardContent() {
        Column() {
            // Image(asset = vectorResource(id = R.drawable.ic_coupon_back), modifier = Modifier.fillMaxWidth())
               Column(modifier = Modifier.padding(8.dp)) {
                      Text(text = coupon.couponTitle, color = Color.Red, fontSize = 20.sp)
                      Text(text = coupon.couponSubTitle, color = Color.Black, fontSize = 13.sp)
                      Text(text = coupon.couponDateTitle, color = Color.Gray, fontSize = 11.sp)
               }
        }
    }
}
      
 
Related