Flutter —— 弹性盒子布局&状态管理&项目搭建
1. Stack
创建一个StackDemo。
class StackDemo extends StatelessWidget {
const StackDemo({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
color:Colors.yellow,
alignment:Alignment(0,0),
child: Stack(
),
);
}
}
为Stack添加三个子部件Container,然后里面添加Icon。
return Container(
color:Colors.yellow,
alignment:Alignment(0,0),
child: Stack(
children: [
Container(
color: Colors.white,
width: 100,
height: 200,
child: Icon(Icons.add),
),
Container(
color: Colors.white,
width: 100,
height: 200,
child: Icon(Icons.seven_k),
),
Container(
color: Colors.white,
width: 100,
height: 200,
child: Icon(Icons.qr_code),
),
],
),
);
运行后发现这里只显示了一个QRcode,这是因为stack是允许子组件堆叠。因为这里大小相同所以被最后一个子部件遮挡住了。
修改大小后,发现这里确实堆叠了起来。
2. Positioned
Positioned用于根据Stack的四个角来确定子组件的位置。将刚才的三个container用 Positioned包起来,然后设置位置属性。
Positioned(
child: Container(
color: Colors.white,
width: 200,
height: 200,
child: Icon(Icons.add),
)),
Positioned(
left: 20,
top: 20,
child: Container(
color: Colors.red,
width: 100,
height: 100,
child: Icon(Icons.seven_k),
)),
Positioned(
right: 0,
child: Container(
color: Colors.blue,
width: 50,
height: 50,
child: Icon(Icons.qr_code),
)),
发现位置按照想要的位置属性改变了。
位置的变化还可以使用margin。那么什么时候用margin什么时候用positioned呢?如果只是为了挪动位置,那么就用positioned,如果要和外界的部件保持边距,就用margin。如果用margin的话,如果外面是一个Expand,那么会因为margin的变化而增加大小。
3. AspectRatio
AspectRatio可以提供父部件一个宽高比。AspectRatio中aspectRatio是必传的属性。
return Container(
color: Co