In Jetpack compose, what is difference using in BasicTextField for textStyle property LocalTextStyle or MaterialTheme?

I've this question, maybe trivial, setting up BasicTextField textStyle property,for set text color for example, I can use one of this 3:

textStyle = TextStyle(color = Color.White)

textStyle = LocalTextStyle.current.copy(color = Color.White)

textStyle = MaterialTheme.typography.body1.copy(color = Color.White)

someone could explain me the difference pros/cons? Thank you in advance

1 answer

  • answered 2022-05-04 10:20 Jakoss

    textStyle = TextStyle(color = Color.White)

    This one is just using hardcoded style for composable. Nothing fancy

    textStyle = LocalTextStyle.current.copy(color = Color.White)

    This one is copying style that is provided by a CompositionLocal via composable higher up in the hierarchy. The advantage is that you do not hardcode anything about the style in your composable. Instead - higher composable is providing the style dynamically for you. Disadvange - the LocalTextStyle might not be set. Although MaterialTheme containers (like Surface, Button or Scaffold) sets that one for you.

    As an example usage - when you create a MaterialTheme Button you can do a simple Text(text = "whatever") and so not set the style. The text style will be provided automatically by the Button itself, so all of the buttons have the same text styles. This is using LocalTextStyle under the hood

    textStyle = MaterialTheme.typography.body1.copy(color = Color.White)

    This is using a style from a theme (MaterialTheme in this example). The advantage is that you stating you want to use particular style of text. Details about the style are provided by a theme. Cannot think of disadvantages here really, other than binding your composable to the given theme

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum