简体   繁体   中英

Can composable functions call non-composable functions?

I saw the new Jetpack Compose in Android and decided to check it out. I have been trying to understand some basic concepts about composables. My question is: Can composable functions call non-composable functions? I have searched Google to no avail.

My question is: Can composable functions call non-composable functions?

Yes. Pretty much everything in Kotlin winds up as a function call, and most functions available to you are non-composable.

Here is one of Google's bits of sample Compose UI code:

@Composable
fun NewsStory() {
    val image = imageResource(R.drawable.header)
    Column(
        modifier = Modifier.padding(16.dp)
    ) {
        val imageModifier = Modifier
            .preferredHeight(180.dp)
            .fillMaxWidth()

        Image(image, modifier = imageModifier,
                  contentScale = ContentScale.Crop)
        Spacer(Modifier.preferredHeight(16.dp))

        Text("A day in Shark Fin Cove")
        Text("Davenport, California")
        Text("December 2018")
    }
}

In that, the following functions are not @Composable :

  • imageResource()
  • Modifier.padding()
  • Modifier.preferredHeight()
  • Modifier.fillMaxWidth()

The rule is that a function marked with @Composable needs to be called by another function marked as @Composable or one of a small family of end consumers of composable functions. This is reminiscent of coroutines, where suspend functions need to be called by other suspend functions or one of a small family of end consumers of suspend functions (eg, coroutine builders like launch() ).

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