https://kotlinlang.org logo
#compose
Title
# compose
m

Mikael Alfredsson

10/16/2020, 1:05 PM
I wanted to create a selfcontained “show version” component, simplest case would be like this
Copy code
@Composable
    fun versionText(){
        val versionName = packageManager.getPackageInfo(packageName, 0).versionName
        Text(text = versionName)
    }
either this is the completely wrong way to do something like this, or I need some way to know if this composable is currently running in a preview, since the preview engine will not really show anything here (I think it even crashes silently somewhere)
s

steelahhh

10/16/2020, 1:24 PM
The preview probably doesn’t work because it knows nothing about android context, since it’s not running on a device Try extracting access to packageManager outside of the component, passing only the string (in the snippet case) as an argument Otherwise there’s nothing wrong with this code
m

Mikael Alfredsson

10/16/2020, 1:26 PM
in the old view system, we could look for
isInEditMode()
to create a ‘preview’ version of the output. Would be nice to have something similar for code executed under @preview
s

steelahhh

10/16/2020, 1:53 PM
Here comes the beauty of compose – you can easily compose This should come at basically no cost; might be wrong tho, but all the compose material components do this, so it should be quite cheap If you do something like this:
Copy code
@Preview
@Composable
fun VersionTextPreview() {
  VersionTextImpl("1.2.3")
}

@Composable
fun VersionText() {
  val context = ContextAmbient.current.applicationContext
  val packageName = context.packageName
  val versionName = context.packageManager.getPackageInfo(packageName, 0).versionName

  VersionTextImpl(versionName = versionName)
}

@Composable
private fun VersionTextImpl(
  versionName: String
) {
  Text(versionName)
}
That way you both get your preview working, and your public API stays the same
m

Mikael Alfredsson

10/16/2020, 1:56 PM
feels like it could easy be bloated when/if you have many components that does this. a simple flag in the composable context sound for me easier, but I guess that is missing and i thank you for the example.