dart Flutter:如何在SingleChildLayoutDelegate中使用子原始约束

t3irkdon  于 2023-05-11  发布在  Flutter
关注(0)|答案(1)|浏览(135)

我正在使用CustomSingleChildLayout创建一个自定义弹出窗口。弹出窗口小部件将位于覆盖层中。getConstraintsForChild方法返回可能的最大约束,而我希望它返回子对象的原始约束。

详情

这是我用来创建OverlayEntry的方法

void createOverlayEntry() {
  RenderBox renderBox = context.findRenderObject() as RenderBox;

  entry = OverlayEntry(
    builder: (context) {
      return CustomSingleChildLayout(
        delegate: _PopupContentDelegate(
          parentSize: renderBox.size,
          parentOffset: renderBox.localToGlobal(Offset.zero),
          offset: offset,
        ),
        child: child,
      );
    },
  );

  Overlay.of(context).insert(entry);
}

通过下面的实现,我得到了Overlay的完整大小,子进程占用了所有可用空间。

class _PopupContentDelegate extends SingleChildLayoutDelegate {
  final Size parentSize;
  final Offset parentOffset;
  final Offset offset;

  _PopupContentDelegate({
    required this.parentSize,
    required this.parentOffset,
    required this.offset,
  });

  @override
  bool shouldRelayout(covariant SingleChildLayoutDelegate oldDelegate) {
    return this != oldDelegate;
  }

  @override
  BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
    // Should return the original constraints of the child
    return super.getConstraintsForChild(constraints);
  }

  @override
  Offset getPositionForChild(Size size, Size childSize) {
    double dx = 0, dy = 0;

    // Find the ideal vertical position.
    dy = -childSize.height - offset.dy;

    // Find the ideal horizontal position.
    dx = (parentSize.width - childSize.width) / 2 + offset.dx;

    // ...some other calculations

    return parentOffset.translate(dx, dy);
  }
}

如果我向_PopupContentDelegate类传递一个Size参数,我将使用它来构造子类的约束。然而,当我事先不知道孩子的尺寸时,这并不起作用。

jm81lzqq

jm81lzqq1#

class _PopupContentDelegate extends SingleChildLayoutDelegate {
  final Size parentSize;
  final Offset parentOffset;
  final Offset offset;

  _PopupContentDelegate({
    required this.parentSize,
    required this.parentOffset,
    required this.offset,
  });

  @override
  bool shouldRelayout(covariant SingleChildLayoutDelegate oldDelegate) {
    return this != oldDelegate;
  }

  @override
  BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
   
    return BoxConstraints(
      minWidth: 0.0,
      maxWidth: constraints.maxWidth,
      minHeight: 0.0,
      maxHeight: constraints.maxHeight,
    );
  }

  @override
  Offset getPositionForChild(Size size, Size childSize) {
    double dx = 0, dy = 0;

    dy = -childSize.height - offset.dy;

    dx = (parentSize.width - childSize.width) / 2 + offset.dx;

    return parentOffset.translate(dx, dy);
  }
}

相关问题