如何获取子小部件的大小

4
我有一个特殊的需求,允许在滚动视图顶部出现一个包含静态内容的头部小部件。滚动视图应该重叠在头部小部件上,以便可以使用剪辑形状效果。我通过使用堆栈视图实现了这种效果,将头部小部件作为堆栈中的第一项,滚动视图作为顶部元素。滚动视图包含一个列,其中第一个子元素是所需高度的空容器(头部小部件高度减去重叠量)。当传入已知高度作为硬编码参数时,可以实现所需的效果。(注意:我尝试使用Sliver List来完成此操作,但无法实现所需的重叠,以满足产品要求。)
头部小部件包含通过API响应加载的图像。图像的高度可能会变化,因此我需要在运行时确定并相应地调整UI。我认为这不是一个困难的任务,但到目前为止,我还没有找到方法。以下两个图像显示了所需的效果,右侧的图像显示了向上滚动的正确行为。请注意,滚动视图必须与剪辑半径相同程度地重叠头部图像。

enter image description here enter image description here

这将生成列表。`_getComponents` 方法为包含在 `SingleChildScrollView` 中的列提供子部件:
  List<Widget> _getComponents(List<Section> sections, BuildContext context, double? height) {
    List<Widget> widgetList = [
      Container(height: 225) // need to obtain correct height here
    ];
    for (int i = 1; i < sections.length; i++) {
      Section section = sections[i];
      if (section.model != null) {
        switch (section.code) {
          case mediaTypeCode:
            if (section.model.runtimeType == MediaModel) {
              widgetList.add(HeaderComponent(section: section));
            }
            break;
          case articleTypeCode:
            if (section.model.runtimeType == ArticleSectionModel) {
              widgetList.add(TitleContentHeader(
                  model: section.model as ArticleSectionModel));
            }
            break;
        }
      }
    }
    return widgetList;
  }

然后在我的视图小部件中,堆栈构建如下:
return Container(
  color: Colors.white,
  child: Stack(
    children: [
      _getHeader(sections),
      SingleChildScrollView(
        child: Column(
          children: _getComponents(sections!, context, null),
        ),
      ),
    ],
  ),
);

我需要能够获取在_getHeader(sections)中返回的标题高度,并将其传递给_getComponents函数,以便我可以确定滚动视图的正确起始位置。
有人能提供任何见解吗?
或者,您能建议一个插件,以允许上面显示的行为?如上所述,Sliver List没有产生期望的效果。
谢谢!
1个回答

1
您可以使用RenderBox获取小部件的大小:

    import 'package:flutter/material.dart';

    class WidgetPosition {
      getSizes(GlobalKey key) {
        final RenderBox renderBoxRed = key.currentContext.findRenderObject();
        final sizeRed = renderBoxRed.size;
        // print("SIZE: $sizeRed");
        return [sizeRed.width, sizeRed.height];
      }

      getPositions(GlobalKey key) {
        final RenderBox renderBoxRed = key.currentContext.findRenderObject();
        final positionRed = renderBoxRed.localToGlobal(Offset.zero);
        // print("POSITION: $positionRed ");
        return [positionRed.dx, positionRed.dy];
      }
    }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接