dart 拖拽位置应与堆叠的其他位置重叠

wbrvyc0a  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(109)

我希望我的堆栈的第一个定位重叠我的堆栈的第二个小部件,当它被拖到它上面。
在下面的代码示例中,将蓝色容器拖动到红色容器上时,蓝色容器应与红色容器重叠。
在我的真实的情况下,我有很多定位和每一个应该能够重叠的其他时,其拖动。

import 'package:flutter/material.dart';

void main() {
  runApp(const MaterialApp(home: Example()));
}

class Example extends StatefulWidget {
  const Example({Key? key}) : super(key: key);

  @override
  State<Example> createState() => _ExampleState();
}

class _ExampleState extends State<Example> {
  late double xPosWidgetOne = 10;
  late double yPosWidgetOne = 20;

  late double xPosWidgetTwo = 100;
  late double yPosWidgetTwo = 100;

  @override
  Widget build(BuildContext context) {
    return Container(
        color: Colors.white,
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        child: Stack(
          children: [
            Positioned(
              left: xPosWidgetOne,
              bottom: yPosWidgetOne,
              width: 50,
              height: 50,
              child: GestureDetector(
                onPanUpdate: (details) => setState(() {
                  xPosWidgetOne += details.delta.dx;
                  yPosWidgetOne -= details.delta.dy;
                }),
                child: Container(
                  color: Colors.blue,
                ),
              ),
            ),
            Positioned(
              left: xPosWidgetTwo,
              bottom: yPosWidgetTwo,
              width: 50,
              height: 50,
              child: GestureDetector(
                onPanUpdate: (details) => setState(() {
                  xPosWidgetTwo += details.delta.dx;
                  yPosWidgetTwo -= details.delta.dy;
                }),
                child: Container(
                  color: Colors.red,
                ),
              ),
            ),
          ],
        ));
  }
}
tquggr8v

tquggr8v1#

引用自https://api.flutter.dev/flutter/widgets/Stack-class.html
堆栈将按顺序绘制其子项,第一个子项位于底部。如果要更改子项的绘制顺序,可以按新顺序重新生成堆栈。如果按此方式重新排序子项,考虑给予孩子非空密钥。这些键将导致框架将子对象的底层对象移动到新位置,而不是在新位置重新创建它们。
这意味着,您基本上可以将所有小部件放在某个List属性中,根据需要更新元素顺序,并将该List属性传递给Stack的子属性。

相关问题