本文主要介绍 Flutter 布局中的 Padding 、Align 以及 Center 控件。
Align
1. 简介
在其他端的开发,Align 一般都是当做一个控件的属性,并没有拿出来当做一个单独的控件。Align 本身实现的功能并不复杂,设置 child 的对齐方式,例如居中、居左居右等,并根据 child 尺寸调节自身尺寸。
2. 属性
-
alignment:对齐方式,一般会使用系统默认提供的9种方式,但是并不是说只有这9种,例如如下的定义。系统提供的9种方式只是预先定义好的。
-
widthFactor:宽度因子,如果设置的话,Align的宽度就是child的宽度乘以这个值,不能为负数。
-
heightFactor:高度因子,如果设置的话,Align的高度就是child的高度乘以这个值,不能为负数。
3. 实例
1. 效果图
2. 代码
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({
Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Welcome to Flutter',
home: Scaffold(
appBar: AppBar(
title: Text('Align'),
),
body: Container(
height: 120.0,
width: 120.0,
color: Colors.blue.shade50,
child: Align(
alignment: Alignment.topRight,
child: FlutterLogo(
size: 60,
),
),
)
)
);
}
}
Center
1. 简介
Center 继承自 Align,只不过是将 alignment 设置为 Alignment.center,其他属性例如 widthFactor、heightFactor,布局行为,都与Align完全一样,在这里就不再单独做介绍了。Center源码如下,没有设置 alignment 属性,是因为 Align 默认的对齐方式就是居中。
class Center extends Align {
/// Creates a widget that centers its child.
const Center({
Key key, double widthFactor, double heightFactor, Widget child })
: super(key: key, widthFactor: widthFactor, heightFactor: heightFactor, child: child);
}
Padding
1. 简介
Padding在Flutter中用的也挺多的,作为一个基础的控件,功能非常单一,给子节点设置padding属性。写过其他端的都了解这个属性,就是设置内边距属性,内边距的空白区域,也是widget的一部分。
2. 属性
padding:padding的类型为EdgeInsetsGeometry,EdgeInsetsGeometry是EdgeInsets以及EdgeInsetsDirectional的基类。在实际使用中不涉及到国际化,例如适配阿拉伯地区等,一般都是使用EdgeInsets。EdgeInsetsDirectional光看命名就知道跟方向相关,因此它的四个边距不限定上下左右,而是根据方向来定的。
3. 示例代码
new Padding(
padding: new EdgeInsets.all(8.0),
child: const Card(child: const Text('Hello World!')),
)