剪辑堆栈子项

Clip Stack children

如何在它的大小范围内剪辑 Stack 子级。

在此图像中有 3 个网格项目 using orange color 并且每个项目都使用 InkWell 以使用 hover-Method 在堆栈上对齐。 hover:false Pop PoP 小部件对 UI 不可见。使用 align 属性 它可以工作,但如您所见,右上部 GridItem 的 item:2 pop POp 小部件在 Stack<Griditem> 之外可见,我想让它在堆栈之外不可见。我已经使用 clipBehavior: 对每个 Clip enums.

进行了测试

我想在 Stack 之外隐藏 Pop POp 小部件,是的,我需要这种弹出效果。

For Flutter web and I'm using Flutter V2.5.2

当前布局有问题

重现问题的完整代码

import 'package:flutter/material.dart';
void main() => runApp(
      const MaterialApp(
        home: Appp(),
      ),
    );

class Appp extends StatelessWidget {
  const Appp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const BodyX();
  }
}

class BodyX extends StatelessWidget {
  const BodyX({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(body: LayoutBuilder(
      builder: (context, constraints) {
        return GridView.count(
          crossAxisCount: 2,
          children: [
            ...List.generate(
              3,
              (index) => GridItem(
                key: UniqueKey(),
                maxWidth: constraints.maxWidth / 2,
              ),
            ),
          ],
        );
      },
    ));
  }
}

class GridItem extends StatefulWidget {
  const GridItem({
    Key? key,
    required this.maxWidth,
  }) : super(key: key);
  final double maxWidth;
  @override
  State<GridItem> createState() => _AppXState();
}

class _AppXState extends State<GridItem> {
  bool _isHovered = false;

  @override
  Widget build(BuildContext context) {
    print("ItemWidth : ${widget.maxWidth}");
    return SizedBox(
      //though it wont effect here,
      // just finding the size of Grid because it will 1x1
      width: widget.maxWidth,
      height: widget.maxWidth,
      child: InkWell(
        onTap: () {},
        hoverColor: Colors.black,
        onHover: (value) {
          setState(() {
            _isHovered = value;
          });
        },
        child: Stack(
          clipBehavior: Clip.antiAliasWithSaveLayer,
          children: [
            Container(
              color: Colors.deepOrange.withOpacity(.2),
            ),
            AnimatedAlign(
              alignment: Alignment(0, _isHovered ? .7 : 2),
              child: Container(
                padding: const EdgeInsets.all(22),
                color: Colors.greenAccent,
                child: const Text(
                  "Pop POp",
                ),
              ),
              duration: const Duration(
                milliseconds: 200,
              ),
            )
          ],
        ),
      ),
    );
  }
}

如果您不希望 Widget 绘制超出其布局大小,您可以使用 ClipRect 对其进行剪辑。

在您的情况下,您可以将 ClipRect 包裹在 Stack 上,如下所示:

ClipRect(
  child: Stack(
    children: ...
  ),
)

此外,您可以使用 ClipRRect to clip a rounded rectangle shape (circular border) or ClipPath 来裁剪自定义形状,例如三角形。您可以在官方文档中阅读有关这些小部件的更多信息。