1
Canvas(modifier = Modifier.size(91.dp), onDraw = {
                drawCircle(color = MaterialTheme.colorScheme.primary)
            })

Compiler gives an error : @Composable invocations can only happen from the context of a @Composable function and underline colorScheme. Also, I cannot apply my palette to AndroidView, like PieChart. I provided the color scheme through CompositionLocalProvider, like this

  CompositionLocalProvider(
    LocalColors provides colors,
    LocalTextStyles provides textStyles
) {...}

Example:

 AndroidView(factory = { context ->
    PieChart(context).apply {
        layoutParams = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT,
        )
        this.description.isEnabled = false

        this.isDrawHoleEnabled = false
        this.holeRadius = 60f
        this.transparentCircleRadius = 0f
        this.legend.isEnabled = false
        this.setHoleColor(LocalColors.current.OnBackground.toArgb()) //here is an error
    }
},

with the same result. My color scheme depends from dark or lite system colors. How should I fix this?

Foenix
  • 376
  • 4
  • 18

2 Answers2

2

You need to move the MaterialTheme.colors.primary (or colorScheme.primary) outside of the onDraw callback. The onDraw callback is not a composable context but the MaterialTheme.colorScheme propery is composable.

            val primaryColor = MaterialTheme.colors.primary
            Canvas(modifier = Modifier, onDraw = {
                drawCircle(primaryColor)
            })

In the second bit, you don't have a composable context there at all. It looks like in that case, you'd want to do something like this: https://stackoverflow.com/a/14468034/1091864

MrPlow
  • 1,214
  • 10
  • 9
  • 1
    Hm, that was easy! It works for both cases... I move the val color = LocalColors.current.OnBackground .. outside AndroidView and it works now. Thanks! But I do not understand how it could be? this new val color became non composable? – Foenix Feb 10 '23 at 23:30
  • 1
    Think of composable context as being a room you need to be in to be given a bit of information. In order to use MaterialTheme.colors.primary to determine the primary color, you need to be in the composable context room. Once someone tells you that, you can write it down and carry it wherever you go. It's not going to change once you leave the composable context room. So, you went into the composable room, got the primary color, wrote it down, and now you can refer back wherever you are. – MrPlow Feb 16 '23 at 00:41
0

OnBackground.toArgb()) //here is an error - I think you're calling an event 'OnBackground' and not the event result.

Winston
  • 38
  • 6