https://kotlinlang.org logo
Title
c

Colton Idle

02/10/2021, 2:25 AM
Why is it when I try to use
MaterialTheme.colors.*
I get an error of "@Composable invocations can only happen from the context of...", but if I just use a string there instead then it works fine, which shows that my @Composable is actually setup correctly. Code snipipets in thread.
LazyColumn(content = {
    items(
        listOf(
            "test1",
            "test2",
        )
    ) {
        Text(text = it.toString())
    }
})
This works
LazyColumn(content = {
    items(
        listOf(
            MaterialTheme.colors.primary,
            MaterialTheme.colors.onSecondary,
        )
    ) {
        Text(text = it.toString())
    }
})
This does not work.
r

rnett

02/10/2021, 2:29 AM
I don't have the code in front of me, I'm guessing some part
MaterialTheme
of is
@Composable
(because of the ambient). Note that `LazyColumn`'s
content
isn't composable, but the `items`'s content is.
☝️ 1
c

Colton Idle

02/10/2021, 2:33 AM
So what's my solution? I can't use MaterialTheme.colors.* as part of my input data?
a

Adam Powell

02/10/2021, 2:44 AM
/me gazes at the current channel 🤔
☝️ 3
c

Colton Idle

02/10/2021, 2:44 AM
Whoops!
a

Adam Powell

02/10/2021, 2:45 AM
Anyway it's because the LazyColumn content lambda isn't itself a composable function
But the body of the items blocks are
c

Colton Idle

02/10/2021, 2:45 AM
I just want to reference these colors... 😭
a

Adam Powell

02/10/2021, 2:46 AM
Make the list outside of the actual LazyColumn call and reference the captured val inside
c

Colton Idle

02/10/2021, 3:09 AM
Hm. I just pulled it out to a top level var in the file
val list = listOf(
    MaterialTheme.colors.primary,
    MaterialTheme.colors.onSecondary,
)
and it has the same error.
a

Adam Powell

02/10/2021, 3:11 AM
yes, it needs to be in a
@Composable
function.
val list = listOf(
    MaterialTheme.colors.primary,
    MaterialTheme.colors.onSecondary,
)
LazyColumn {
  items(list) {
    // ...
  }
}
c

Colton Idle

02/10/2021, 3:16 AM
It worked. And I dont wanna lie and say im not defeated. lol I feel so stupid. oh well. Thanks @Adam Powell
😅 2