🍉 加载中...


Flutter Baseline 基准线布局组件

3 minute read

Baseline 基准线布局,会将所有的子元素都统一放在同一水平线上,是一个根据子项的基线对它们的位置进行定位的组件 (widget)。其能够让不同的高度的子组件处在规定的基准线上,大多用文字排版中,使不同大小的文字保持在同一水平线。

要点

  • Baseline 子节点是文本,会以文本的TextBaseline为基线,不是文本则已组件底部为基线。
  • Baseline 父节点的内边距,外边距都会对位置产生影响,top 会使位置相对基线下降,bottom 会使位置相对基线上升。
  • Baseline 内部嵌套复杂的布局也会使位置相对基线产生变化。

属性

属性名称 值类型 说明
baseline double 基准线位置,从顶部开始计算,以像素为单位。
baselineType TextBaseline 定位子组件的基准线类型,现有两种类型。alphabetic 对齐字符底部水平线,ideographic 对齐表意字符的水平线。

表意文字描述字符 (ideographic description characters),是 unicode 里面的几个字符。用处是用汉字部件来描述一个组合字。

示例

 1import 'package:flutter/material.dart';
 2
 3void main() {
 4  runApp(const MyApp());
 5}
 6
 7class MyApp extends StatelessWidget {
 8  const MyApp({Key? key}) : super(key: key);
 9
10  @override
11  Widget build(BuildContext context) {
12    return MaterialApp(
13      title: 'Flutter Demo',
14      theme: ThemeData(
15        primarySwatch: Colors.blue,
16      ),
17      home: const MyHomePage(),
18    );
19  }
20}
21
22class MyHomePage extends StatelessWidget {
23  const MyHomePage({Key? key}) : super(key: key);
24
25  @override
26  Widget build(BuildContext context) {
27    return Scaffold(
28      body: Center(
29        child: Column(
30          children: [
31            Row(
32              textBaseline: TextBaseline.alphabetic,
33              verticalDirection: VerticalDirection.up,
34              children: const [
35                Text("data", style: TextStyle(fontSize: 12)),
36                Text("data", style: TextStyle(fontSize: 24)),
37                Text("data", style: TextStyle(fontSize: 36)),
38              ],
39            ),
40            Row(
41              textBaseline: TextBaseline.alphabetic,
42              verticalDirection: VerticalDirection.up,
43              children: const [
44                Baseline(
45                  baseline: 60,
46                  baselineType: TextBaseline.alphabetic,
47                  child: Text("data", style: TextStyle(fontSize: 12)),
48                ),
49                Baseline(
50                  baseline: 60,
51                  baselineType: TextBaseline.alphabetic,
52                  child: Text("data", style: TextStyle(fontSize: 24)),
53                ),
54                Baseline(
55                  baseline: 60,
56                  baselineType: TextBaseline.alphabetic,
57                  child: Text("data", style: TextStyle(fontSize: 36)),
58                ),
59              ],
60            ),
61          ],
62        ),
63      ),
64    );
65  }
66}