【笔记】Flutter的Align对齐组件

前言

Flutter的Align对齐组件学习笔记

Align对齐组件

alignment:子元素的位置

Alignment.topLeft:左上
Alignment.topCenter:上
Alignment.topRight:右上
Alignment.centerLeft:左
Alignment.center:中
Alignment.centerRight:右
Alignment.bottomLeft:左下
Alignment.bottomCenter:下
Alignment.bottomRight:右下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import 'package:flutter/material.dart';

void main() {
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("文本内容"),
),
body: const App(),
),
));
}

class App extends StatelessWidget {
const App({super.key});

@override
Widget build(BuildContext context) {
return Container(
width: 200,
height: 200,
color: Colors.red,
child: Align(
alignment: Alignment.center,
child: Container(
width: 100,
height: 100,
color: Colors.yellow,
),
),
);
}
}

自定义子元素的位置

  • 通过给定x轴和y轴的坐标,实现自定义子元素的位置
    • x轴和y轴的取值范围为[0,1]
    • 左上角为原点,x轴向右为正方向,y轴向下为正方向
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import 'package:flutter/material.dart';

void main() {
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("文本内容"),
),
body: const App(),
),
));
}

class App extends StatelessWidget {
const App({super.key});

@override
Widget build(BuildContext context) {
return Container(
width: 200,
height: 200,
color: Colors.red,
child: Align(
alignment: const Alignment(1, 1),
child: Container(
width: 100,
height: 100,
color: Colors.yellow,
),
),
);
}
}

完成

参考文献

哔哩哔哩——筱筱知晓