Is this possible to have data class that has constructor parameter which default value is set to some @Composable val
? Something like this:
data class MyStyle(
val marginTop: Dp = 8.dp,
val marginBottom: Dp = 16.dp,
val myTextStyle: TextStyle = MaterialTheme.typography.body1
)
Error:
@Composable invocations can only happen from the context of a @Composable function
CodePudding user response:
No, it's not allowed. If try to add @Composable
to any constructor, you'll get this:
This annotation is not applicable to target 'constructor'
This is because recomposition can happen many times during the view life cycle, down to a single frame during animation, in which case creating new objects for each recomposition can degrade the performance of your application. Check out more about recomposition in Thinking in Compose.
Instead you should use remember
to store the value between recompositions. You can pass all variables which may change as keys to remember
, so the value will be recalculated only when needed:
@Composable
fun rememberMyStyle(
marginTop: Dp = 8.dp,
marginBottom: Dp = 16.dp,
myTextStyle: TextStyle = MaterialTheme.typography.body1,
) = remember(marginTop, marginBottom, myTextStyle) {
MyStyle(marginTop, marginBottom, myTextStyle)
}