简体   繁体   English

如何检查 flutter 中的两个小部件是否重叠?

[英]How to check if two widgets are overlapping in flutter?

I wanted to know if we can check if two widgets in flutter are overlapping.我想知道我们是否可以检查 flutter 中的两个小部件是否重叠。 I actually have two AnimatedContainer stacked using Stack.我实际上有两个使用 Stack 堆叠的 AnimatedContainer。 I wanted to check if the children of the two overlap.我想检查两者的孩子是否重叠。 I actually am creating a game from scratch and wanted to check collisions.我实际上是从头开始创建游戏并想检查碰撞。 Though x's and y's are an option, but it depends on height and width of the two objects and as they are having different, so results are very inaccurate.虽然 x's 和 y's 是一个选项,但它取决于两个对象的高度和宽度,并且由于它们具有不同,因此结果非常不准确。

Any help would be appreciated.任何帮助,将不胜感激。

You can pass a key to the widget and then use key.currentContext.findRenderObject() to get the render object.您可以将key传递给小部件,然后使用key.currentContext.findRenderObject()来获取渲染 object。

Here is a working examlpe这是一个工作示例

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) => MaterialApp(home: MyPage());
}

class MyPage extends StatefulWidget {
  @override
  _MyPageState createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> with WidgetsBindingObserver {
  final containerKey1 = GlobalKey();
  final containerKey2 = GlobalKey();

  Alignment box2Align = Alignment.topRight;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Stack(
          children: [
            Align(
              alignment: Alignment.topLeft,
              child: Container(
                key: containerKey1,
                color: Colors.pink,
                width: 100.0,
                height: 100.0,
              ),
            ),
            Align(
              alignment: box2Align,
              child: Transform.translate(
                offset: const Offset(10.0, 10.0),
                child: Container(
                  key: containerKey2,
                  color: Colors.purple.withOpacity(0.75),
                  width: 100.0,
                  height: 100.0,
                ),
              ),
            ),
            // Buttons
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                FlatButton(
                  color: Colors.yellow,
                  child: Text('Move containers'),
                  onPressed: () => setState(() {
                    if (box2Align == Alignment.topRight)
                      box2Align = Alignment.topLeft;
                    else
                      box2Align = Alignment.topRight;
                  }),
                ),
                FlatButton(
                  color: Colors.yellow,
                  child: Text('Check if boxesCollide'),
                  onPressed: _onCheckTap,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  void _onCheckTap() {
    RenderBox box1 = containerKey1.currentContext.findRenderObject();
    RenderBox box2 = containerKey2.currentContext.findRenderObject();

    final size1 = box1.size;
    final size2 = box2.size;

    final position1 = box1.localToGlobal(Offset.zero);
    final position2 = box2.localToGlobal(Offset.zero);

    final collide = (position1.dx < position2.dx + size2.width &&
        position1.dx + size1.width > position2.dx &&
        position1.dy < position2.dy + size2.height &&
        position1.dy + size1.height > position2.dy);

    print('Containers collide: $collide');
  }
}

I'm trying to figure out how to make a minimal game engine as a learning exercise and this example was helpful, but wouldn't compile in dartpad.我试图弄清楚如何制作一个最小的游戏引擎作为学习练习,这个例子很有帮助,但不会在 dartpad 中编译。 I've updated the example provided by YoBo to be compatible with DartPad as of 08/29/2022 here:我已经更新了 YoBo 提供的示例,以便在 2022 年 8 月 29 日与 DartPad 兼容:

https://dartpad.dev/?id=82c20c9d19d54d8f640601ab0b13ddb5 https://dartpad.dev/?id=82c20c9d19d54d8f640601ab0b13ddb5

Thanks YoBo!谢谢优博!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM