面试题答案
一键面试使用Positioned组件指定位置
- 偏移量控制:
- 在Flutter的
Stack
布局中,Positioned
组件用于精确控制子组件的位置。它有left
、top
、right
和bottom
属性来指定子组件相对于Stack
边界的偏移量。 - 例如:
Stack( children: [ Positioned( left: 50, top: 100, child: Container( width: 200, height: 200, color: Colors.blue, ), ), ], );
- 在上述代码中,
Container
组件在Stack
中,从左边缘偏移50像素,从上边缘偏移100像素。
- 在Flutter的
不使用Positioned组件时子组件的默认位置规则
- 堆叠顺序:
- 当子组件不使用
Positioned
组件时,它们会按照在children
列表中的顺序堆叠,后添加的子组件会覆盖先添加的子组件。 - 例如:
Stack( children: [ Container( width: 200, height: 200, color: Colors.blue, ), Container( width: 100, height: 100, color: Colors.red, ), ], );
- 这里
Colors.red
的Container
会覆盖Colors.blue
的Container
的部分区域,因为它在children
列表中排在后面。
- 当子组件不使用
- 位置:
- 不使用
Positioned
的子组件默认会对齐Stack
的左上角,且按照自身大小进行显示,不会根据父Stack
大小自动调整,除非子组件本身有布局相关的设置(如Align
等)。
- 不使用