MST

星途 面试题库

面试题:Flutter中Stack布局层级管理基础

在Flutter的Stack布局中,如何调整子Widget的层级顺序?请举例说明使用什么属性及如何操作。
13.4万 热度难度
前端开发Flutter

知识考点

AI 面试

面试题答案

一键面试

在Flutter的Stack布局中,可以通过Stackchildren参数的顺序来调整子Widget的层级顺序,先添加的子Widget在底层,后添加的在顶层。

例如:

Stack(
  children: [
    // 这是底层的Widget
    Container(
      color: Colors.blue,
      width: 200,
      height: 200,
    ),
    // 这是顶层的Widget
    Container(
      color: Colors.red,
      width: 100,
      height: 100,
    ),
  ],
)

上述代码中,蓝色的Container先添加,处于底层,红色的Container后添加,处于顶层。

另外,还可以使用Positioned组件来控制子Widget的位置和层级。例如:

Stack(
  children: [
    Positioned(
      left: 0,
      top: 0,
      child: Container(
        color: Colors.blue,
        width: 200,
        height: 200,
      ),
    ),
    Positioned(
      left: 50,
      top: 50,
      child: Container(
        color: Colors.red,
        width: 100,
        height: 100,
      ),
    ),
  ],
)

这里同样是蓝色Container在底层,红色Container在顶层。Positioned只是额外控制了子Widget在Stack中的位置。