如何在绘制之前知道小部件的大小? [英] How to know the size of a widget before painting it?

查看:18
本文介绍了如何在绘制之前知道小部件的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 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 行的文本).

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.

提前谢谢你!

推荐答案

我最终通过使用 Offstage 小部件非常适合这种情况.

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 如果您在 ColumnRow 中使用它.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆