Why is there only ".sp" in fontSize of Text("") composable and not ".dp" in Jetpack Compose-beta08

Viewed 2851

I want the size of the text to be in .dp so that it doesn't change according to the system font. How to achieve this in Jetpack Compose "Text" composable

2 Answers

The Compose team does not intend to provide that possibility, em are a bit pita to use, but there is an easy workaround should anyone really need it.

@Composable
fun dpToSp(dp: Dp) = with(LocalDensity.current) { dp.toSp() }

Text("ABCD", fontSize = dpToSp(15.dp))

Taken from the same issue tracker: https://issuetracker.google.com/190644747.

You can use extension properties:

private fun Int.textDp(density: Density): TextUnit = with(density) {
    this@textDp.dp.toSp()
}


val Int.textDp: TextUnit
    @Composable get() =  this.textDp(density = LocalDensity.current)
Related