Search code examples
android-jetpack-composeandroid-camerax

Call a Composable function from an onClick that is in a Composable


I have a page where i have a compose card that has a onClick:

Card(
         modifier = Modifier
           .width(cardWidth)
           .height(cardHeight)
           .padding(cardPadding),
           onClick = { Camera.Preview() },
           content = {
              //Code
            }

But the problem i have is that i get error: "@Composable invocations can only happen from the context of a @Composable function" Since Camera.Preview() is a Composable function:

object Camera {

@Composable
fun Preview(
    modifier: Modifier = Modifier,
    scaleType: PreviewView.ScaleType = PreviewView.ScaleType.FILL_CENTER,
    cameraSelector: CameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
) {
//Code
}

how do i call Camera.Preview() from the onClick event without getting this error.


Solution

  • To show a Composable after a click, do it as follows:

    @Composable
    fun MainComposable() {
    
        var showPreview by remember { mutableStateOf(false) }
    
        Column(
            modifier = Modifier.fillMaxSize()
        ) {
    
            if (showPreview) {
                Preview()
            }
    
            Card(
                modifier = Modifier
                    .width(cardWidth)
                    .height(cardHeight)
                    .padding(cardPadding),
                onClick = { showPreview = true },
                content = {
                    //Code
                }
            }
        }
    }
    

    Once you click on the Card, you will set the showPreview variable to true. This will trigger a recomposition, the if statement becomes true, and the Preview Composable will be shown.

    Also, it is not common place Composables into objects, as you are doing right now with the Camera object. Just place it as a normal function into the .kt file.