Mohamed Elfiky
10/21/2020, 12:11 PMjim
10/21/2020, 1:19 PMkey
.
Otherwise, if you fail to hoist your state, then key
is needed when you emit widgets within a for
loop (directly or indirectly). In such a case, you need to use key
to tell Compose the identity of each widget, so the state of the widget can be correctly associated with the intended widget on screen. Otherwise, state may be accidentally transferred to the wrong widget. React.js has a similar concept of keys, and this jsfiddle demonstrates the state transference problem pretty well: http://jsfiddle.net/frosas/S4Dju/
If your widget state is not hoisted, then within every loop, you will need to wrap each widget in a key
and pass in a unique identifier for that widget (an ID for example). For example, if I had a bookstore, I would use the ISBN number as the key for each book.
for(book in books) {
key(book.isbn) {
Box(...) {
...
Text(book.title)
Text(book.description)
...
}
}
}
Mohamed Elfiky
10/21/2020, 4:34 PMjim
10/21/2020, 5:29 PMclass MyWidgetBlackBoxState {
internal var animationSpring = ...
}
@Composable
fun MyWidget(state: MyWidgetBlackBoxState = MyWidgetBlackBoxState()) {
...
}
By making the state hoistable in this way, it opens a bunch of options (like reparenting, allowing a parent to control the animation, allowing for the coordination of the animation with other animations, etc) which makes it a generally nice practice.Alexjlockwood
10/21/2020, 6:57 PM