Flutter Stack 做页面切换

发布时间 2023-11-03 15:19:36作者: 行走的泡泡鱼

从名字上看,这个容器就是堆。
效果是能让自己内部的子组件重叠放置,严格意义上来说,我认为他可以算是一个布局容器,就像Row,Column一样。
下面是网上找的例子(主要我懒的现写了)

class CustomStack extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var yellowBox = Container(
      color: Colors.yellow,
      height: 100,
      width: 100,
    );

    var redBox = Container(
      color: Colors.red,
      height: 90,
      width: 90,
    );

    var greenBox = Container(
      color: Colors.green,
      height: 80,
      width: 80,
    );

    return Container(
      width: 200,
      height: 120,
      color: Colors.grey.withAlpha(33),
      child: Stack(
        textDirection: TextDirection.rtl,
        fit: StackFit.loose,
        alignment: Alignment.topRight,
        children: <Widget>[yellowBox, redBox, greenBox],
      ),
    );
  }
}

实际效果就是三块颜色跌在一起,像下面这样。
image

它有下面这些常用属性
● Alignment
● Positioned 这个好像算是组件,目前我还没用过
● clipBehavior 如果设置为None,可以不剪切超过边界的部分
● Align 和上面的Alignment看起来功能重复,但看人家的示例好像有不一样的地方

当然我不是为了抄人家的说明,而是要记录我的用法。
目标:实现点击不同的选项,切换不同的页面来显示。
我采用了IndexedStack来做, 这样在点了按钮之后,就会修改_index, 然后重画不同的page

List<Widget> _UserManageChildPages = [
  UserPage(),
  IdentityPage(),
  AuthorityPage(),
];

child: IndexedStack(
  index: _index,
  children: _UserManageChildPages,
),

child: ElevatedButton(
  onPressed: () {
    setState(() {
      _index = 1;
    });
  },
  child: Text('Identity')
),

今天还看到了一种做法,直接使用Stack

int rightMenu = 1;

Stack(
  alignment: AlignmentDirectional.center,
  children: <Widget>[
  rightMenu==1?UserPage():rightMenu==2?IdentityPage():rightMenu==3?AuthorityPage(),
)

看起来一样可以达到效果。
不过不知道是不是因为我自己找的方法,个人更倾向用前面这种。