I want the first Positioned of my Stack to Overlap the Second Widget of my Stack, when it is dragged over it.
In the code example below the blue container should overlap the red container, when its dragged over it.
In my real case, I have a lot of Positioned and each one should be able to overlap the other ones when its dragged.
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,
),
),
),
],
));
}
}
Quote from https://api.flutter.dev/flutter/widgets/Stack-class.html
The stack paints its children in order with the first child being at the bottom. If you want to change the order in which the children paint, you can rebuild the stack with the children in the new order. If you reorder the children in this way, consider giving the children non-null keys. These keys will cause the framework to move the underlying objects for the children to their new locations rather than recreate them at their new location.
That means, that you could basically have all your widgets in some List property, update element orders as you wish, and pass that List property to the Stack's child property.