As you can see in this Stack the yellow cube is at the bellow of a purple cube.
when I click, I want to change the index of the yellow cube to transform it from index 0 to 1 and the purple cube from index 1 to 0, vice versa.
I tried IndexedStack but it's only showing a single child from a list of children.
class _FlipIndex extends State<FlipIndex> {
int currentIndex = 0;
@override
Widget build(BuildContext context) {
return Center(
child: GestureDetector(
onTap: (){
// Change Z-Index of widget
},
child: Stack(
alignment: Alignment.center,
children: [
Transform.translate(
offset: Offset(-30.0, 0.0),
child: Container(
width: 100,
height: 100,
decoration: BoxDecoration(
color: Colors.yellow,
shape: BoxShape.rectangle,
),
),
),
Transform.translate(
offset: Offset(30.0, 0.0),
child: Container(
width: 100,
height: 100,
decoration: BoxDecoration(
color: Colors.purple,
shape: BoxShape.rectangle,
),
),
),
],
),
),
);
}
}
try this:
class _FlipIndex extends State<FlipIndex> {
List<Widget> _stackChildren = [];
int currentIndex = 0;
@override
void initState() {
super.initState();
_stackChildren.add(_stackChild(Colors.yellow, 30));
_stackChildren.add(_stackChild(Colors.green, -30));
}
//call this function for swapping items
void _swapOrder() {
Widget _first = _stackChildren[0];
_stackChildren.removeAt(0);
_stackChildren.add(_first);
setState(() {});
}
Widget _stackChild(Color childColor, double xOffset) {
return Transform.translate(
key: UniqueKey(),
offset: Offset(xOffset, 0.0),
child: Container(
width: 100,
height: 100,
decoration: BoxDecoration(
color: childColor,
shape: BoxShape.rectangle,
),
),
);
}
@override
Widget build(BuildContext context) {
return Center(
child: GestureDetector(
onTap: () {
_swapOrder();
},
child: Stack(
alignment: Alignment.center,
children: _stackChildren,
),
),
);
}
}