【问题标题】:Flutter: How to dry-render a widget and get its size?Flutter:如何干渲染一个小部件并获得它的大小?
【发布时间】:2022-11-06 03:20:52
【问题描述】:

我正在尝试获取小部件的大小。一种常见的方法是给一个小部件GlobalKey(),并检索它的大小在布局并显示给用户之后.鉴于约束 (MediaQuery.of(context).size.width),有没有办法在构建真正的小部件之前预渲染小部件并获取其大小(特别是高度)?

编辑:我非常想要高度,因为我需要将高度传递给SliverAppBar。我可以先构建内容,然后在布局后使用setState 调整大小。但这也意味着屏幕会闪烁一次。

【问题讨论】:

  • 这不是 IntrinsicHeight/Width 所做的吗?
  • 不,我需要一个号码。
  • 那么,看看酒吧里的 Boxy。
  • 更新了帖子
  • 也许Custom[Single|Multi]ChildLayout 是你需要的?

标签: flutter widget


【解决方案1】:

您可以尝试后台小部件。所以布局看起来像

Offstage(
 offstage: true,
 child: Container (
   key: widgetKey
 )
)

【讨论】:

  • 尽管如此,我还是无法获得initState 的高度,我需要在渲染真实高度之前获得高度。使用后台意味着真实的和后台的将同时构建。
  • 你不能让它处于初始化状态
  • Offset 可能有用,但我必须以一种非常老套的方式来做。
  • 是的,绝对
【解决方案2】:

您可以使用 Offstage。诀窍是使用Offstage 进行渲染,然后在使用postframecallback 获得大小时重新加载。

class _wrapperState extends State<wrapper> with WidgetsBindingObserver
{
    Size? widgetSize;
    GlobalKey widgetKey = GlobalKey();
    late Widget sourceWidget;

    @override
    void initState()
    {
        WidgetsBinding.instance.addObserver(this);

        // widget.child is your main widget you're trying to get the size.
        sourceWidget = widget.child;

        super.initState();
    }

    @override
    Widget build(BuildContext context)
    {
        WidgetsBinding.instance.addPostFrameCallback((_)
        {
            if (widgetSize == null)
            {
                setState(()
                {
                    widgetSize = widgetKey.currentContext!.size;
                });
            }
        });

        // Assign a key to your widget so that we can get its size later.
        // Also this key will prevent the widget to get built twice.
        Widget finalWidget = KeyedSubtree(
            key: widgetKey,
            child: sourceWidget
        );

        // If we don't have the size, then do the offstage.
        // Postframe will kick off right after this.
        if (widgetSize == null)
        {
            return Offstage(
                child: Material(
                    body: Stack(
                        children: [
                            Positioned(
                                top: 0,
                                left: 0,
                                child: finalWidget,
                            )
                        ],
                    ),
                ),
            );
        }

        // Now we do have our size.
        // Do your main build now.
        return MyComplexWidget();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-20
    • 1970-01-01
    • 2019-07-11
    • 1970-01-01
    • 2021-09-01
    • 2017-09-25
    • 2022-12-04
    • 1970-01-01
    相关资源
    最近更新 更多