Reputation: 17746
I’m trying to use an AnimatedContainer
for just a simple animation of an expand effect (similar to ExpandableTile
) when the user press it.
My issue is that this container, when expanded, can have either 10.0 height, or 1000.0 (it must be dynamic). Ok, to animate it, it needs to know the height before-hand, makes sense. But how would I know the max height of something before rendering it (I’m going to render Text which can have 1 to N lines)).
I’ve think in a lot of possibilities, but none seem to fit. Most of the times we get the size from something that is already rendered, from the RenderBox
, not the opposite, so this is kind bugging me.
Thank you in advance!
Upvotes: 2
Views: 1878
Reputation: 17746
I end up finding the solution by using the Offstage widget which fits perfectly in this scenario.
Wrapping the subtree in a Offstage
and assigning it a key (can be a GlobalKey
), then, before actually rendering it, I can get its height by doing:
void _getWidgetHeight() {
if (subtreeHeight == null) {
RenderBox renderBox = key.currentContext.findRenderObject();
subtreeHeight = renderBox.size.height;
}
setState(() {
_isOffstage = false;
});
}
this way, if you have an AnimatedContainer
, for example, and need to animate to its final size, you can have the following:
AnimatedContainer(
duration: Duration(milliseconds: 250),
height: subtreeHeight ?? 100.0 // some default size,
...
)
and it will render accordingly.
As a note, make sure the content in your subtree can be inserted inside the Container
while it is animating (eg. wrapping the Offstage
in a Flexible
if you´re using it in a Column
or Row
).
Upvotes: 6