简体   繁体   中英

Jetpack compose AppBarIcon complains that "Functions which invoke @Composable functions must be marked with the @Composable"

I used jetpack compose AppBarIcon element but I got the error: Functions which invoke @Composable functions must be marked with the @Composable" when I call a composable function on the onclick lamba. This is the code:

class testActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent { AppBarIcon(Image(10, 10) ) {
                composableFunction()
            }
        }
    }
} 

@Composable()
fun composableFunction() {
}

and it is a real problem becaus I got an exception at run-time

It is somethink I miss or it is a real bug ?

First thing to note that Composable function must only be called inside another Composable function .
Now back to your question, onClick parameter which accept the function is not a composable function. So calling @Composable function inside a onClick isn't the option and hence throw an error Functions which invoke @Composable functions must be marked with the @Composable .
Code to resolve this issue.

class testActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    setContent {
        var loadView = +state { false }
        Column {
            AppBarIcon(+imageResource(R.drawable.dashboard)) {
                loadView.value = true
            }
            Text("Hey")
            if (loadView.value)
                composableFunction()
        }
    }
  }
}
@Composable()
fun composableFunction() {
    Text("appbar content")
}

Reason because onClick is not composable: All Composable function are called at the same time to compose the UI completely.While onClick is called later after the UI is already composed. So you need to use the state to recompose the UI and load composable function after onClick occur.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM