Using compose on Android and I can not find this i...
# compose
r
Using compose on Android and I can not find this in the docs any where. Had an issue where a
Text
composable was not getting
MaterialTheme
colors unless it is also wrapped in a
Scaffold
as shown below. Does that sound right that you need
Scaffold
with the
MaterialTheme
to get the colors to work or do i have a config issue somewhere?
Copy code
// Does not get theme colors
MaterialTheme { Text("test") }

// Gets theme colors
MaterialTheme { Scaffold { Text("Test") } }
c
Yes you can use that or Surface. Surface is really the key Composable you need at some point of the hierarchy to cascade the text colors from MaterialTheme (without setting it explicitly via params on Text)
🙌 1
Scaffold has a Surface within it I believe. As do other Material components like Card
s
If you go one layer deep into the
Text
Composable you’ll see that it gets the color like this:
Copy code
val textColor = color.takeOrElse {
  style.color.takeOrElse {
    LocalContentColor.current.copy(alpha = LocalContentAlpha.current)
  }
}
Which means that if you don’t specify it explicitly it tries to look at the
LocalContentColor
. Now if you’re at a place in your composable tree where that does not exist, I guess it would simply take the default which is Color.Black. Now guess what
Scaffold
or
Surface
do? Something like:
Copy code
(in params) color: Color = MaterialTheme.colors.surface,
CompositionLocalProvider(
  LocalContentColor provides contentColor
)
Reading the compose source code sometimes feels like a maze, but very often is super straightforward and can help you understand a lot of things! This is one of them!
🙌 2
r
@Chris Sinco [G] @Stylianos Gakis thank you both for the responses. This is kind of fascinating as its not explicitly documented well but is how its done in every example. I am also still learning that unlike with xml / activities you can actually go into source and read it clearly. 🙂 thanks again!
c
Yeah it’s something we could improve in our theming docs. cc @Nick Rout
r
Its kind of a grey area. if you look all the snippets in the docs have either a surface (or a scaffold) under the material theme in hierarchy so my assumption was that you need one from that but it was never explicitly called out. Thank you again for the response here. Very excited with everything compose has been so far and really excited for the future!
🙏 1