面试题答案
一键面试Stack布局机制
- 堆叠特性:
Stack
允许子组件相互堆叠,后添加的子组件会堆叠在前面子组件之上。它就像一个画布,子组件按照添加顺序在同一空间内叠加排列。 - 布局规则:
Stack
本身的大小默认由其非定位(没有使用Positioned
包裹)的子组件决定。如果所有子组件都是定位的,Stack
会尽可能小,包裹住其子组件。
Positioned属性对元素定位的影响
- left、right、top、bottom属性:这些属性用于指定子组件相对于
Stack
边界的偏移量。left
表示子组件距离Stack
左边界的距离。right
表示子组件距离Stack
右边界的距离。top
表示子组件距离Stack
上边界的距离。bottom
表示子组件距离Stack
下边界的距离。- 如果同时设置了
left
和right
,left
优先级高;同理,top
优先级高于bottom
。
- width和height属性:用于指定子组件的宽度和高度。如果不设置,子组件会根据自身内容大小自适应。
示例
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Stack和Positioned示例'),
),
body: Stack(
children: <Widget>[
Container(
color: Colors.blue,
width: double.infinity,
height: double.infinity,
),
Positioned(
left: 50,
top: 100,
child: Container(
color: Colors.red,
width: 200,
height: 200,
),
),
Positioned(
right: 30,
bottom: 80,
child: Container(
color: Colors.green,
width: 150,
height: 150,
),
)
],
),
),
);
}
}
在这个例子中,Stack
有三个子组件。第一个是一个充满屏幕的蓝色 Container
,作为背景。另外两个 Container
分别使用 Positioned
进行定位。红色的 Container
距离左边界 50
,距离上边界 100
,宽高均为 200
;绿色的 Container
距离右边界 30
,距离下边界 80
,宽高为 150
。这样通过 Stack
和 Positioned
的协同工作,实现了精准的布局控制。