Flutter布局Alignment Container类详解
2023-12-12 01:38:54
Flutter布局Alignment Container类里有一个alignment属性,翻译过来应该叫对齐方式,这个属性用来控制Container的子控件相对于它自身的一个位置。在我们iOS开发中,相当于设置控件的contentMode属性,在UIView的API文档中,contentMode共有四种:UIViewContentModeScaleToFill,UIViewContentModeScaleAspectFit,UIViewContentModeScaleAspectFill和UIViewContentModeRedraw。
在Flutter布局中,Alignment Container类里的alignment属性可以设置子控件在容器中的位置,具体位置由两个参数来决定,一个是水平位置,一个是垂直位置,水平位置有九个取值,左,中,右,左上,上中,右上,左下,中下和右下,垂直位置有九个取值,左,中,右,左上,上中,右上,左下,中下和右下。
我们通过代码实例来学习如何使用Alignment Container类里的alignment属性。
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Container(
width: 200,
height: 200,
color: Colors.red,
alignment: Alignment.center,
child: Text('Flutter布局Alignment Container类'),
),
),
),
);
}
}
在这个代码实例中,我们创建了一个Container,设置它的宽度为200,高度为200,颜色为红色,并设置它的对齐方式为居中,然后在这个Container里放了一个Text控件,Text控件的文本内容为"Flutter布局Alignment Container类"。
运行这个代码实例,你会看到一个红色的Container,Container的中间有一个居中的Text控件。
我们可以通过修改Container的alignment属性来改变Text控件的位置,比如将Container的alignment属性设置为Alignment.topLeft,那么Text控件就会移动到Container的左上角。
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Container(
width: 200,
height: 200,
color: Colors.red,
alignment: Alignment.topLeft,
child: Text('Flutter布局Alignment Container类'),
),
),
),
);
}
}
运行这个代码实例,你会看到一个红色的Container,Container的左上角有一个Text控件。
我们可以通过修改Container的alignment属性来改变Text控件的位置,我们可以尝试不同的对齐方式来实现不同的布局效果。