[英]How to programmatically change Z-Index of widget Stack in Flutter
正如您在此堆栈中看到的那样,黄色立方体位于紫色立方体的下方。
当我单击时,我想更改黄色立方体的索引以将其从索引 0 转换为 1,将紫色立方体从索引 1 转换为 0,反之亦然。
我尝试了 IndexedStack,但它只显示了一个孩子列表中的一个孩子。
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,
),
),
),
],
),
),
);
}
}
尝试这个:
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,
),
),
);
}
}
试试这个 package https://pub.dev/packages/indexed
示例图片:
此 package 允许您使用 CSS 中的z-index
index
类的索引对堆栈内的项目进行排序。
您可以通过更改index
属性轻松更改项目的顺序
这是它如何工作的示例
Indexer(
children: [
Indexed(
index: 100,
child: Positioned(
//...
)
),
Indexed(
index: 1000,
child: Positioned(
//...
)
),
Indexed(
index: 3,
child: Positioned(
//...
)
),
],
);
如果您使用的是一些复杂小部件的块,您可以扩展或实现IndexedInterface
class 并覆盖index
获取器:
class IndexedDemo extends IndexedInterface {
int index = 5;
}
或实现
class IndexedDemo extends AnimatedWidget implements IndexedInterface {
int index = 1000;
//...
//...
}
然后像Indexed
class 小部件一样使用它:
Indexer(
children: [
IndexedDemo(
index: 100,
child: Positioned(
//...
)
),
IndexedFoo(
index: 1000,
child: Positioned(
//...
)
),
],
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.