The Code A is from the official sample code here.
I know that in order to preserve state across recompositions, remember the mutable state using remember.
I think that the code val extraPadding by animateDpAsState(...)
should be val extraPadding by remember { animateDpAsState(...) }
, is it right?
BTW, val extraPadding by remember { animateDpAsState(...) }
will cause the error
Composable calls are not allowed inside the calculation parameter of inline fun remember(calculation: () -> TypeVariable(T)): TypeVariable(T)
Code A
@Composable
private fun Greeting(name: String) {
var expanded by remember { mutableStateOf(false) }
val extraPadding by animateDpAsState( //Should I add remember
if (expanded) 48.dp else 0.dp
)
Surface(
color = MaterialTheme.colors.primary,
modifier = Modifier.padding(vertical = 4.dp, horizontal = 8.dp)
) {
Row(modifier = Modifier.padding(24.dp)) {
Column(modifier = Modifier
.weight(1f)
.padding(bottom = extraPadding)
) {
Text(text = "Hello, ")
Text(text = name)
}
OutlinedButton(
onClick = { expanded = !expanded }
) {
Text(if (expanded) "Show less" else "Show more")
}
}
}
}
CodePudding user response:
No, you shouldn't. This function is marked with @Composable
so it should be used directly in the view builder.
animateDpAsState
will calculate its value depending on targetValue
on each recomposition.
If you check it source code you'll see, that it uses remember
inside, that's why it's marked with @Composable
, and that's why you shouldn't bother about remembering some values manually.