目录
1.Flex弹性布局
类似html中的flex布局策略。
1.1Flex
Flex组件可以沿着水平或垂直方向排列子组件。Row和Column都继承了Flex,参数基本相同。
Flex功能更为强大。构造器参数:
Flex({
...
required this.direction, //弹性布局的方向, Row默认为水平方向,Column默认为垂直方向
List<Widget> children = const <Widget>[],
})
1.2Expanded
其只能作为Flex的子组件,因为Row和Column都继承了Flex,所以Expanded也能作为它们的子组件。
Expanded可以按比例扩展Flex子组件所占用的空间。构造器:
const Expanded({
int flex = 1,
required Widget child,
})
flex参数值若为0或null,则不会扩展空间;大于0则按比例扩展。
示例:
class FlexExpandedWidget extends StatelessWidget {
const FlexExpandedWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Flex(
direction: Axis.horizontal,
children: <Widget>[
Expanded(
flex: 1,
child: Container(
height: 50,
color: Colors.red,
),
),
Expanded(
flex: 2,
child: Container(
height: 50,
color: Colors.blue,
),
),
],
)
],
);
}
}
效果图:
2.流式布局
2.1Wrap
其构造器:
Wrap({
...
this.direction = Axis.horizontal,
this.alignment = WrapAlignment.start,
this.spacing = 0.0,
this.runAlignment = WrapAlignment.start,
this.runSpacing = 0.0,
this.crossAxisAlignment = WrapCrossAlignment.start,
this.textDirection,
this.verticalDirection = VerticalDirection.down,
List<Widget> children = const <Widget>[],
})
介绍几个特有参数:
spacing,主轴方向子widget的间距;
runSpacing,纵轴方向间距;
runAlignment,纵轴方向的对齐方式;
return Wrap(
spacing: 10,
runSpacing: 10,
alignment: WrapAlignment.center,
children: const <Widget>[
Text('flutter'),
Text('flutter'),
Text('flutter'),
Text('flutter'),
Text('flutter'),
Text('flutter'),
Text('flutter'),
Text('flutter'),
Text('flutter'),
Text('flutter'),
Text('flutter'),
Text('flutter'),
Text('flutter'),
Text('flutter'),
],
);
效果图:
3.层叠布局
类似web中的绝对定位,子组件可以根据距父组件四个角的距离来确定其位置。
3.1Stack
构造器:
Stack({
this.alignment = AlignmentDirectional.topStart,
this.textDirection,
this.fit = StackFit.loose,
this.clipBehavior = Clip.hardEdge,
List<Widget> children = const <Widget>[],
})
alignment,对于没有定位(没有Positioned)的或部分定位(指没有在某个轴上定位)的子组件该如何对齐;
textDirection,用于确定alignment对齐的参考系;
fit,用于确定没有定位的子组件如何适应Stack的大小;
clipBehavior,决定超出Stack大小的部分如何剪裁;
3.2Positioned
const Positioned({
Key? key,
this.left,
this.top,
this.right,
this.bottom,
this.width,
this.height,
required Widget child,
})
left、top、right、bottom代表距离Stack各边的距离。
width、height稍有不同,可以配合left、top、right、bottom来定位组件。如水平方向只能指定left、right、width中的两个,另一个会自动算出:指定了left,width后rigth就是left+width。
return ConstrainedBox(
constraints: const BoxConstraints.expand(),
child: Stack(
// 对于部门定位或没有Positioned会居中
alignment: Alignment.center,
children: <Widget>[
Container(
child: const Text('center'),
),
const Positioned(
left: 20,
child: Text('left'),
),
const Positioned(
right: 30,
child: Text('right'),
)
],
),
);
}