在绘制小部件之前如何知道小部件的大小? [英] How to know the size of a widget before painting it?
问题描述
我正尝试将 AnimatedContainer
用于当用户按下扩展效果时的简单动画(类似于 ExpandableTile
).
I’m trying to use an AnimatedContainer
for just a simple animation of an expand effect (similar to ExpandableTile
) when the user press it.
我的问题是,此容器在展开时可以具有10.0的高度或1000.0的高度(它必须是动态的).好吧,要制作动画,它需要事先知道高度,这是有道理的.但是在渲染之前如何知道某物的最大高度(我将渲染可以有1到N行的Text).
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)).
我认为有很多可能性,但似乎没有一个合适的选择.在大多数情况下,我们是从 RenderBox
渲染的东西中获取尺寸的,而不是相反的,所以这很困扰我.
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.
提前谢谢!
推荐答案
I end up finding the solution by using the Offstage widget which fits perfectly in this scenario.
将子树包装在 Offstage
中并为其分配一个键(可以是 GlobalKey
),然后,在实际渲染它之前,我可以通过以下操作获得其高度:
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;
});
}
这样,例如,如果您有一个 AnimatedContainer
,并且需要为其最终大小设置动画,则可以具有以下内容:
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,
...
)
,它将相应地呈现.
请注意,确保子树中的内容在动画时可以插入 Container
中(例如,将 Offstage
包裹在 Flexible中
(如果您在 Column
或 Row
)中使用它.
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
).
这篇关于在绘制小部件之前如何知道小部件的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!