Flutter Scaffold 组件全属性说明
Scaffold 是 Material Design 的基础布局组件,提供 AppBar、Drawer、FAB、BottomNavigationBar 等常见结构。以下为完整属性与解释。
🎨 基础视觉结构
1. appBar
类型: PreferredSizeWidget?
页面顶部的 AppBar(标题栏、导航栏),通常使用 AppBar() 构建。
2. body
类型: Widget?
Scaffold 的主体内容区域。
3. backgroundColor
类型: Color?
整个 Scaffold 的背景色。
4. extendBody
类型: bool = false
若为 true,body 会延伸到 bottomNavigationBar 后面。
5. extendBodyBehindAppBar
类型: bool = false
若为 true,body 会延伸到 appBar 后面(常用于透明 AppBar 布局)。
🧭 导航栏 / 侧边栏
6. drawer
类型: Widget?
左侧抽屉菜单。
7. onDrawerChanged
类型: void Function(bool)?
Drawer 打开/关闭状态回调。
8. drawerScrimColor
类型: Color?
Drawer 打开时背景遮罩层的颜色。
9. drawerEdgeDragWidth
类型: double?
从边缘滑动打开 Drawer 的触发距离。
10. drawerEnableOpenDragGesture
类型: bool = true
是否允许从左侧边缘拖动打开 Drawer。
11. endDrawer
类型: Widget?
右侧抽屉菜单。
12. onEndDrawerChanged
类型: void Function(bool)?
右侧 Drawer 打开/关闭事件。
13. endDrawerEnableOpenDragGesture
类型: bool = true
是否允许从右侧拖动打开 endDrawer。
🎛️ 底部区域
14. bottomNavigationBar
类型: Widget?
底部导航栏。
15. bottomSheet
类型: Widget?
固定在底部的 BottomSheet。
🎚️ 浮动按钮(FAB)
16. floatingActionButton
类型: Widget?
FAB 按钮。
17. floatingActionButtonLocation
类型: FloatingActionButtonLocation?
FAB 的具体位置(例如 centerDocked)。
18. floatingActionButtonAnimator
类型: FloatingActionButtonAnimator?
FAB 动画行为。
📑 SnackBar / BottomSheet 控制
19. persistentFooterButtons
类型: List<Widget>?
固定在底部的一组按钮(通常用于对话框操作区)。
20. resizeToAvoidBottomInset
类型: bool?
键盘弹出时是否自动调整布局避免遮挡内容。
21. primary
类型: bool = true
控制 body 是否占据系统状态栏下的全部空间。
🧩 手势与 SafeArea
22. drawerDragStartBehavior
类型: DragStartBehavior
控制 Drawer 的手势拖动行为。
⚙️ 高级属性
23. restorationId
类型: String?
用于状态恢复(如 Scroll、Tab 的位置)。
24. key
类型: Key?
Widget 唯一标识。
📑 属性总表(速查)
| 属性名 | 类型 | 说明 |
|---|---|---|
| key | Key? | Widget 标识 |
| appBar | PreferredSizeWidget? | 顶部栏 |
| body | Widget? | 主体内容 |
| floatingActionButton | Widget? | FAB 按钮 |
| floatingActionButtonLocation | FloatingActionButtonLocation? | FAB 位置 |
| floatingActionButtonAnimator | FloatingActionButtonAnimator? | FAB 动画 |
| persistentFooterButtons | List? | 底部固定按钮 |
| drawer | Widget? | 左侧抽屉菜单 |
| onDrawerChanged | void Function(bool)? | Drawer 状态回调 |
| endDrawer | Widget? | 右侧抽屉菜单 |
| onEndDrawerChanged | void Function(bool)? | endDrawer 状态回调 |
| bottomNavigationBar | Widget? | 底部导航栏 |
| bottomSheet | Widget? | 底部 Sheet |
| backgroundColor | Color? | 背景色 |
| resizeToAvoidBottomInset | bool? | 键盘遮挡处理 |
| primary | bool | 是否占据整个顶部区域 |
| drawerDragStartBehavior | DragStartBehavior | Drawer 手势行为 |
| extendBody | bool | body 伸到 navBar 后 |
| extendBodyBehindAppBar | bool | body 伸至 appBar 后 |
| drawerScrimColor | Color? | Drawer 遮罩层颜色 |
| drawerEdgeDragWidth | double? | Drawer 边缘触发宽度 |
| drawerEnableOpenDragGesture | bool | 左抽屉滑动开启 |
| endDrawerEnableOpenDragGesture | bool | 右抽屉滑动开启 |
| restorationId | String? | 状态恢复 |
Flutter Positioned 组件全属性说明
Positioned 是 Flutter 中用于 Stack 内绝对定位子组件 的布局组件。
通过 top/left/right/bottom/width/height 等属性,可控制子组件在 Stack 中的精确位置和大小。
📌 Positioned 主要属性(含解释)
1. left
类型: double?
子组件距离 Stack 左侧的距离。
2. top
类型: double?
子组件距离 Stack 顶部的距离。
3. right
类型: double?
子组件距离 Stack 右侧的距离。
4. bottom
类型: double?
子组件距离 Stack 底部的距离。
⚠️ 若设置了相对两个方向的属性(如同时设置 left + right),则宽度不需要设置,组件会自动拉伸至两边。
📏 大小约束属性
5. width
类型: double?
子组件宽度。
如果设置了左右距离 (left + right),则不能再设置 width,否则报错。
6. height
类型: double?
子组件高度。
同理,如果设置了 top + bottom,不能再设置 height。
🧩 高级位置属性(仅二选一的参数组)
7. child
类型: Widget
被定位的子组件。
🧭 特殊构造函数(Positioned.fill)
Positioned.fill
让子组件填满整个 Stack,可再设置 optional padding:
dart
Positioned.fill(
top: 10,
left: 20,
child: ...
)
等同于:
-
top = 10
-
left = 20
-
right = 0
-
bottom = 0
Flutter ClipRRect 组件全指南(可完整复制版)
ClipRRect 用于按圆角矩形裁剪子组件。
1. 基本用法示例
less
ClipRRect(
borderRadius: BorderRadius.circular(16),
child: Image.network("https://example.com/pic.jpg"),
)
2. 属性总表
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| borderRadius | BorderRadius | BorderRadius.zero | 圆角半径 |
| clipper | CustomClipper? | null | 自定义裁剪器 |
| clipBehavior | Clip | Clip.antiAlias | 裁剪方式 |
| child | Widget | ------ | 被裁剪的内容 |
3. 属性解释
3.1 borderRadius
设置圆角:
css
borderRadius: BorderRadius.circular(20)
单独设置某些角:
css
borderRadius: BorderRadius.only(
topLeft: Radius.circular(12),
bottomRight: Radius.circular(30),
)
3.2 clipper
使用自定义裁剪器:
scala
class MyClipper extends CustomClipper<RRect> {
@override
RRect getClip(Size size) {
return RRect.fromRectAndRadius(
Rect.fromLTWH(0, 0, size.width, size.height),
Radius.circular(40),
);
}
@override
bool shouldReclip(oldClipper) => false;
}
3.3 clipBehavior
| 值 | 效果 |
|---|---|
| Clip.none | 不裁剪 |
| Clip.hardEdge | 无抗锯齿,性能最好 |
| Clip.antiAlias | 默认抗锯齿 |
| Clip.antiAliasWithSaveLayer | 最美观但性能最差 |
3.4 child
被裁剪的任何组件(图片、按钮、Container 等)。
4. 常见示例
圆角图片
less
ClipRRect(
borderRadius: BorderRadius.circular(12),
child: Image.asset("images/avatar.jpg"),
)
圆形头像
less
ClipRRect(
borderRadius: BorderRadius.circular(999),
child: Image.asset("images/avatar.jpg", width: 80, height: 80),
)
不同角不同圆角
less
ClipRRect(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(24),
bottomRight: Radius.circular(6),
),
child: Container(color: Colors.blue, width: 120, height: 120),
)
自定义裁剪器
less
ClipRRect(
clipper: TicketClipper(),
child: Container(height: 100, color: Colors.orange),
)
5. 注意事项
ClipRRect有开销,能不用裁剪就用装饰圆角(BoxDecoration)- 列表大量使用时避免
Clip.antiAliasWithSaveLayer - 与模糊过滤(BackdropFilter)组合时需使用 saveLayer
- 对图片裁剪最常见、最推荐
6. 速查表
| 场景 | 推荐方式 |
|---|---|
| 普通圆角 | borderRadius |
| 圆形头像 | borderRadius.circular(999) |
| 自定义形状 | clipper |
| 列表性能优先 | Clip.hardEdge |
| 模糊背景 | Clip.antiAliasWithSaveLayer |
Flutter BackdropFilter 组件详解(可一键复制版)
BackdropFilter 用于对其后面已经绘制的内容 应用图像滤镜(例如模糊、颜色矩阵等),常用于实现毛玻璃 / 模糊背景效果(frosted glass)。
注意:BackdropFilter 是对"已经在它后面绘制的像素"进行处理,而不是处理它的 child 本身。
1. 构造器与属性总表
构造器签名(核心):
scss
BackdropFilter({
Key? key,
required ImageFilter filter,
Widget? child,
})
| 属性 | 类型 | 必须 | 说明 |
|---|---|---|---|
| key | Key? | 否 | 标准 Widget key |
| filter | ImageFilter | 是 | 要应用的图像滤镜(例如 ImageFilter.blur(...) 或 ImageFilter.matrix(...)) |
| child | Widget? | 否 | 子 Widget。通常 child 是一个带有半透明背景的容器,用于表现"玻璃"效果;也可以为空。 |
2. 工作原理(关键点)
BackdropFilter会 捕获并处理"它在渲染树中的区域内且在它之前绘制的像素",把处理后的像素绘制到该区域,然后再绘制它的 child(如果有)。- 换句话说:背景(在 BackdropFilter 之前绘制的内容) → 应用 filter → 绘制 child。
- 它不会影响 child 自己的内容(child 是在滤镜之后绘制的)。
- 如果想限制滤镜影响的范围,需要使用裁剪(如
ClipRect/ClipRRect/OverflowBox等)把区域限定住;否则滤镜可能会影响更大的区域或者没有效果(因为没有被裁剪的绘制区域)。
3. 常见 ImageFilter 用法
-
模糊(最常见):
lessImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0) -
颜色矩阵(复杂图像处理):
scssImageFilter.matrix(...) // 需要配合 dart:ui Matrix4/ColorFilter 等
注意:
ImageFilter来源于dart:ui,某些 filter 需要组合ColorFilter/BlendMode或使用ImageFiltered(处理 child 本身)实现不同效果。
4. 常见用法范例(可直接复制)
基本毛玻璃背景(通常与 Stack + Positioned 结合)
less
Stack(
children: [
// 背景
Image.network('https://example.com/bg.jpg', fit: BoxFit.cover, width: double.infinity, height: double.infinity),
// 局部毛玻璃
Positioned(
left: 40,
top: 100,
child: ClipRRect(
borderRadius: BorderRadius.circular(16),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 8.0, sigmaY: 8.0),
child: Container(
width: 280,
height: 140,
color: Colors.white.withOpacity(0.2),
child: Center(child: Text('Frosted glass')),
),
),
),
),
],
)
全屏毛玻璃遮罩(比如对整个背景模糊)
less
Stack(
children: [
// 背景内容
...,
// 全屏模糊(注意:一般用在半透明遮罩中)
BackdropFilter(
filter: ImageFilter.blur(sigmaX: 6, sigmaY: 6),
child: Container(
color: Colors.black.withOpacity(0.2),
),
),
],
)
5. 必知注意事项(性能 / 行为 / 限制)
-
必须裁剪才能限定滤镜范围
BackdropFilter会影响其 布局区域内 的"之前绘制像素"。若没有裁剪,滤镜可能看起来没有作用或影响超出预期区域。常见做法是把BackdropFilter包在ClipRect/ClipRRect中(如示例所示)。
-
性能开销较大
- 模糊等滤镜会生成额外的绘制开销,尤其 sigma 值大或频繁重绘时。尽量:
- 使用较小的 sigma
- 将需要模糊的区域限制最小
- 避免在 ListView/滚动中频繁重建包含复杂滤镜的 subtree
- 模糊等滤镜会生成额外的绘制开销,尤其 sigma 值大或频繁重绘时。尽量:
-
与
BackdropFilter组合的 child 通常半透明- 通常 child 使用
Container(color: Colors.white.withOpacity(0.2))或带透明度的装饰,以实现"玻璃"外观。
- 通常 child 使用
-
BackdropFilter不会模糊 child 自身- 如果你需要模糊 child 本身,请使用
ImageFiltered或ImageFilter作用于 child。BackdropFilter专注于"背景(下层)"。
- 如果你需要模糊 child 本身,请使用
-
绘制顺序重要
- BackdropFilter 只会处理它在绘制顺序之前的内容(即绘制在它"之后"的 child 不会被处理)。在 Stack 中,确保背景先绘制,再放置 BackdropFilter。
-
与平台渲染有关
- 在某些情况下,硬件加速、saveLayer、透明度组合会影响最终效果。若配合
BackdropFilter使用透明度或模糊,Flutter 可能需要创建 saveLayer,从而增加开销。
- 在某些情况下,硬件加速、saveLayer、透明度组合会影响最终效果。若配合
-
不要把大型模糊放在频繁重构的 widget 中
- 若父 widget 频繁 rebuild,会导致滤镜重算,影响性能。
6. BackdropFilter 与 ImageFiltered 的区别
- BackdropFilter:处理"背后的像素"(背景)→ 然后绘制 child。常用于毛玻璃背景效果。
- ImageFiltered :处理 child 自身 的像素(对 child 进行滤镜),不会影响后面的背景。
根据需求选择:
- 要模糊背景 →
BackdropFilter - 要模糊当前 widget 本身 →
ImageFiltered
7. Debug / 调试建议
- 在调试性能时,使用 Flutter 的性能工具(Performance/Timeline)查看是否产生额外的 GPU 上传或 saveLayer。
- 在开发中先将 sigma 设置为较小值验证效果,再逐步调大以避免一次性过高开销。
8. 小结(快捷要点)
BackdropFilter(filter: ImageFilter..., child: ...):模糊或处理它后面的绘制内容(不是 child 本身)。- 常配合
ClipRect/ClipRRect来限制影响范围。 - 是实现"毛玻璃"效果的首选,但要注意性能。
- 若需要处理 child 自身,使用
ImageFiltered。
参考示例(最简可复制片段)
less
ClipRect(
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
child: Container(
color: Colors.white.withOpacity(0.1),
width: 200,
height: 100,
child: Center(child: Text('Blurred background')),
),
),
)
Flutter Column 组件 --- 完整属性说明与详解(可一键复制)
本文档覆盖 Column 的所有构造器参数(属性)、每项属性的详细解释、常见取值、示例与注意事项,帮助你快速掌握 Column 的使用与陷阱。
注意:
Column来自package:flutter/widgets.dart,用于按垂直方向排列子 Widget。Column本身不滚动 ,当内容超出空间请使用ListView或把子项包在SingleChildScrollView/Expanded/Flexible中。
构造器签名(核心参数)
(以下列出 Column 常见构造器参数及默认值)
ini
const Column({
Key? key,
MainAxisAlignment mainAxisAlignment = MainAxisAlignment.start,
MainAxisSize mainAxisSize = MainAxisSize.max,
CrossAxisAlignment crossAxisAlignment = CrossAxisAlignment.center,
TextDirection? textDirection,
VerticalDirection verticalDirection = VerticalDirection.down,
TextBaseline? textBaseline,
double spacing = 0.0,
List<Widget> children = const <Widget>[],
})
属性清单与详解
key --- Key?
- 作用:标准 Flutter Widget key,用于标识 Widget、保持 state、控制元素重用。
- 使用场景 :当 Column 的位置或子列表会重排时(例如在列表中动态增删),使用
Key(通常是ValueKey/ObjectKey/UniqueKey)能避免状态错配。
mainAxisAlignment --- MainAxisAlignment(默认 MainAxisAlignment.start)
-
主轴 :对于
Column,主轴是垂直方向(top → bottom)。 -
作用:控制 children 在主轴(垂直)上的排列方式和空间分配。
-
常用值:
start:从顶部开始排列(默认)。end:从底部开始排列。center:在垂直方向居中排列。spaceBetween:第一个放顶部,最后一个放底部,其他平均分布间距。spaceAround:每个子项周围间隔相等(首尾的间隔为中间间隔的一半)。spaceEvenly:所有间隔(包括首尾)都相等。
-
示例:
Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ ... ], )
mainAxisSize --- MainAxisSize(默认 MainAxisSize.max)
- 作用:控制 Column 在主轴方向(垂直)上占据的空间是尽可能大还是仅包裹子项高度。
- 取值 :
MainAxisSize.max:尽可能占用父可用的最大高度(默认)。MainAxisSize.min:尽可能紧凑,只占用子项所需高度。
- 注意 :在 Column 内放
Expanded/Flexible会影响占用空间行为;当没有被约束(比如放在 ListView 中)可能出现unbounded constraints 错误,需把 Column 包在具有边界的父控件或使用ShrinkWrap风格布局。
crossAxisAlignment --- CrossAxisAlignment(默认 CrossAxisAlignment.center)
-
交叉轴 :对于
Column,交叉轴是水平方向(left ↔ right)。 -
作用:定义 children 在水平方向(交叉轴)如何对齐或拉伸。
-
常用值:
start:靠交叉轴"起始"对齐(左或右,取决于textDirection)。end:靠交叉轴"结束"对齐。center:水平居中(默认)。stretch:拉伸使子项在交叉轴方向填满(若子项没有明确宽度)。baseline:按文本基线对齐(仅对含文本的子项有意义,需要设置textBaseline)。
-
示例:
Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Container(height: 40, color: Colors.red), Container(height: 40, color: Colors.blue), ], )
textDirection --- TextDirection?
- 作用 :用于区分
start/end在交叉轴(水平)上的含义(LTR 或 RTL)。 - 默认值 :如果未提供,则使用最近的
Directionality(环境方向)。 - 注意 :如果没有 ambient
Directionality且代码中需要区分start/end,则必须显式传入textDirection,否则会抛异常或无法确定对齐方向。
verticalDirection --- VerticalDirection(默认 VerticalDirection.down)
-
作用:决定 children 在主轴(垂直)上的布局顺序与起点位置(垂直方向的"起点"是在上方还是下方)。
-
取值:
VerticalDirection.down:从上到下布局(默认行为)。VerticalDirection.up:从下到上布局(第一个 child 在底部)。
-
示例:
Column( verticalDirection: VerticalDirection.up, children: [...], )
textBaseline --- TextBaseline?
-
类型 :
TextBaseline.alphabetic或TextBaseline.ideographic。 -
作用 :当
crossAxisAlignment == CrossAxisAlignment.baseline时,textBaseline必须非空,指定使用哪个文本基线对齐子项(不同文字/语言的字体基线可能不同)。 -
示例:
Column( crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: [Text('A'), Text('g')], )
spacing --- double(默认 0.0)
-
说明 :该参数在新版 Flutter API 中可用(在 Flex 超类上),表示子项之间的固定间距(在主轴方向上)------相当于在每对相邻 children 之间插入固定大小的空白。
-
作用 :当你想要子项之间有固定间隔时,可直接设置
spacing,不必手动在 children 中插入 SizedBox。 -
示例:
Column( spacing: 12.0, children: [WidgetA(), WidgetB(), WidgetC()], )
注:并非所有 Flutter 版本都包含
spacing;如果你的 SDK 中没有该参数,等价写法是手动插入SizedBox(height: x)在 children 之间,或使用Wrap/ListView.separated等。
children --- List<Widget>
- 作用:Column 要垂直排列的子 Widgets 列表。
- 默认:空列表。
- 注意 :Column 不滚动,如果 children 总高度可能超过可用空间,需要:
- 将外层包装
SingleChildScrollView(要注意尺寸约束),或 - 使用
Expanded/Flexible控制填充/收缩,或 - 使用
ListView等可滚动容器。
- 将外层包装
常见错误与陷阱(必看)
- 内容溢出(RenderFlex overflow) :当 Column 的总高度超过父容器限制时,会抛出黄色/黑色溢出条纹错误。解决办法:使用
Expanded/Flexible、把 Column 包在SingleChildScrollView,或改用ListView。 - unbounded constraints :把 Column 放到需要无限高度的地方(例如
ListView的 item 中),可能触发约束错误。通常需要限定高度或使用IntrinsicHeight/SizedBox等。 - Cross-axis baseline 对齐 :使用
CrossAxisAlignment.baseline时必须提供textBaseline,否则会出错。 - start/end 受 TextDirection 影响 :使用
start/end时要意识到 RTL(右到左)布局对齐会反转。 - 不要在 Column 内大量使用
antiPattern的 nested Column:深度嵌套过多会让布局复杂且难以管理,尽量提取为组合组件或使用布局工具(Grid/Flex/Wrap)。
常用示例(可直接复制,示例内使用缩进代码块避免嵌套反复)
1. 基本 Column(默认行为)
less
Column(
children: [
Text('Item 1'),
Text('Item 2'),
Text('Item 3'),
],
)
2. 垂直居中并在子项间均匀分布
less
Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text('Top'),
Text('Middle'),
Text('Bottom'),
],
)
3. 交叉轴拉伸(宽度填满父容器)
less
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ElevatedButton(onPressed: (){}, child: Text('Button 1')),
ElevatedButton(onPressed: (){}, child: Text('Button 2')),
],
)
4. 使用 spacing(若你的 Flutter SDK 支持)
less
Column(
spacing: 16.0,
children: [
Text('A'),
Text('B'),
Text('C'),
],
)
5. 基线对齐(文本对齐)
less
Column(
crossAxisAlignment: CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
children: [
Text('Small', style: TextStyle(fontSize: 12)),
Text('Large', style: TextStyle(fontSize: 28)),
],
)
6. 可滚动内容(示例:把 Column 放在 SingleChildScrollView)
less
SingleChildScrollView(
child: Column(
children: List.generate(30, (i) => Text('Item $i')),
),
)
速查表(Cheat Sheet)
| 属性 | 类型 | 默认 | 用途速览 |
|---|---|---|---|
| key | Key? | --- | 标识 Widget,保持 state |
| mainAxisAlignment | MainAxisAlignment | start | 控制主轴(垂直)上的排列方式与间距策略 |
| mainAxisSize | MainAxisSize | max | 决定 Column 占用主轴空间的策略(max/min) |
| crossAxisAlignment | CrossAxisAlignment | center | 控制交叉轴(水平)对齐/拉伸 |
| textDirection | TextDirection? | 环境 Directionality | 决定 start/end 的含义(LTR/RTL) |
| verticalDirection | VerticalDirection | down | 决定 children 从上到下还是从下到上布局 |
| textBaseline | TextBaseline? | null | 与 baseline 对齐配合使用 |
| spacing | double | 0.0 | 子项之间的固定间距(若 SDK 支持) |
| children | List | [] | 要排列的子 Widget 列表 |
推荐阅读与调试技巧
- 阅读 Flutter 官方 Layout 文档(
Row/Column部分)理解主/交叉轴概念。 - 使用 Flutter Inspector(DevTools)观察实际布局盒模型与约束。
- 在出现 overflow 时,启用 debugPaintSizeEnabled(或在 DevTools 中开启显示布局边界)来定位问题。
需要哪一种我就生成哪一种。 ::contentReference[oaicite:0]{index=0}
bash
# Flutter `Container` 组件 --- 全属性详解(可一键复制版)
Container 是 Flutter 中最常用的布局和装饰类 Widget。它是一个多功能容器,结合了对齐、填充、尺寸约束、装饰(背景、边框、阴影)、变换等能力。虽然看起来很强大,但也有一些优先级和性能注意点需要了解。
构造器签名(常见参数)
下面是 Container 的常见构造器参数(摘要形式):
css
const Container({
Key? key,
AlignmentGeometry? alignment,
EdgeInsetsGeometry? padding,
Color? color,
Decoration? decoration,
Decoration? foregroundDecoration,
double? width,
double? height,
BoxConstraints? constraints,
EdgeInsetsGeometry? margin,
Matrix4? transform,
AlignmentGeometry? transformAlignment,
Clip clipBehavior = Clip.none,
Widget? child,
})
说明:实际源码中
Container有若干重载和内部行为,这里列出的是使用最广的属性集合与默认值。
属性详解(逐项)
key --- Key?
- 作用:标准 Widget key,用于 Flutter 元素树定位、状态保持、列表重排时身份识别。
- 何时用 :当
Container在动态列表中顺序会改变,想保持子 Widget 状态时使用Key。
alignment --- AlignmentGeometry?
-
作用 :当
child的尺寸小于Container可用尺寸时,控制 child 在 container 内如何对齐(例如居中、左上、右下等)。 -
常用值:
Alignment.centerAlignment.topLeftAlignment.bottomRightAlignmentDirectional.centerStart(依赖 textDirection)
-
注意:
- 若
width/height或constraints未定义且没有父约束,alignment 会影响容器尺寸(Container 会尽可能包裹 child)。
- 若
-
示例:
Container( width: 200, height: 100, alignment: Alignment.center, child: Text('Centered'), )
padding --- EdgeInsetsGeometry?
-
作用 :内边距,给 child 与 container 边界之间添加空白(相当于在 child 外包一层
Padding)。 -
常用构造:
EdgeInsets.all(8)EdgeInsets.symmetric(horizontal: 12, vertical: 8)EdgeInsets.only(left: 10)
-
示例:
Container( padding: EdgeInsets.all(12), child: Text('Padded'), )
color --- Color?
-
作用:快速设置背景色。
-
注意事项:
color只是decoration的简写;当同时提供color与decoration时会抛异常 (二者冲突)。如果需要背景色和其他装饰(边框、圆角、阴影),应把颜色放到decoration: BoxDecoration(color: ...)。
-
示例(仅颜色):
Container( color: Colors.blue, child: ... )
decoration --- Decoration?(如 BoxDecoration)
-
作用:完整的外观控制:背景色、渐变、图片、边框、圆角、阴影等。
-
常见类型 :
BoxDecoration(...)最常用。 -
示例:
Container( decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(12), boxShadow: [BoxShadow(blurRadius: 8, color: Colors.black26)], border: Border.all(color: Colors.grey.shade300), ), child: ... )
foregroundDecoration --- Decoration?
-
作用 :类似
decoration,但绘制在 child 之上(前景层)。可以用于覆盖半透明效果、前景边框、图案等。 -
示例:
Container( decoration: BoxDecoration(color: Colors.blue), foregroundDecoration: BoxDecoration( gradient: LinearGradient(...).withOpacity(0.2), ), child: ... )
width, height --- double?
-
作用:显式设置容器的宽度和/或高度。
-
与 constraints 的交互:
- 如果同时提供
width/height和constraints,它们会被合并为最终约束,冲突时会抛异常或被约束限制。
- 如果同时提供
-
示例:
Container(width: 120, height: 80, color: Colors.red)
constraints --- BoxConstraints?
-
作用:更细粒度控制尺寸(最小/最大宽高、固定大小等)。
-
常用方法:
BoxConstraints.tight(Size(100, 50))(固定尺寸)BoxConstraints(minWidth: 50, maxWidth: 200)
-
示例:
Container( constraints: BoxConstraints(maxWidth: 200, minHeight: 40), child: ... )
margin --- EdgeInsetsGeometry?
-
作用 :外边距,容器与父级/兄弟控件之间的间距(相当于外部包裹一层
Padding或SizedBox)。 -
示例:
Container( margin: EdgeInsets.symmetric(vertical: 8, horizontal: 16), child: ... )
transform --- Matrix4?
-
作用:对容器(包括其子 Widget)应用 2D/3D 变换(旋转、缩放、平移、倾斜等)。
-
注意:
- 变换可能会影响绘制顺序和性能。
- transformOrigin 可通过
transformAlignment控制。
-
示例(旋转):
Container( transform: Matrix4.rotationZ(0.1), child: ... )
transformAlignment --- AlignmentGeometry?
-
作用 :指定
transform的对齐基点(默认以容器左上角或中心为变换原点,取决于该值)。 -
常见值 :
Alignment.center、Alignment.topLeft等。 -
示例:
Container( transformAlignment: Alignment.center, transform: Matrix4.rotationZ(0.2), child: ... )
clipBehavior --- Clip(默认 Clip.none)
-
作用 :当容器使用
decoration(带圆角或形状)或transform时,决定是否裁剪溢出部分以及裁剪的质量(硬切/抗锯齿等)。 -
取值:
Clip.none(不裁剪,最快)Clip.hardEdge(硬裁剪)Clip.antiAliasClip.antiAliasWithSaveLayer(更平滑但性能更差)
-
示例:
Container( decoration: BoxDecoration(borderRadius: BorderRadius.circular(8)), clipBehavior: Clip.antiAlias, child: ... )
child --- Widget?
- 作用:容器内的子 Widget,可以是任意 Widget(文本、图片、布局等)。
- 注意 :
- 如果没有
child,Container可能会尽可能小或由width/height/constraints决定尺寸。
- 如果没有
Container 的行为优先级与常见陷阱(重要)
- color 与 decoration 冲突 :若同时提供
color和decoration(非 null),会抛异常。解决:把 color 放到decoration: BoxDecoration(color: ...)中,或仅使用 color。 - alignment 在无 child 时的行为:当没有 child 且没有宽高/constraints 限制时,alignment 不会产生作用;如果有 child 且父提供足够空间,alignment 控制子的位置。
- decoration 会让容器变成有图层 :使用
decoration(尤其带圆角、阴影)可能导致需要clipBehavior或saveLayer,从而影响性能。 - transform 与布局约束 :
transform是绘制阶段的变换(不会改变布局阶段的大小与位置约束),但视觉上会影响占位效果。 - 避免在列表 item 里滥用复杂 decoration/clip:在大量重复项时,尽量减少高开销的装饰(如 large boxShadow 或 anti-aliased clipping)。
常见使用示例(缩进代码块以保证一键复制可靠)
1. 带圆角、阴影和背景色的卡片
less
Container(
margin: EdgeInsets.all(12),
padding: EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(color: Colors.black26, blurRadius: 8, offset: Offset(0,4)),
],
),
child: Text('Card content'),
)
2. 固定尺寸 + 居中文本
less
Container(
width: 200,
height: 80,
alignment: Alignment.center,
color: Colors.blue,
child: Text('Centered', style: TextStyle(color: Colors.white)),
)
3. 使用 transform(旋转)
less
Container(
width: 120,
height: 60,
alignment: Alignment.center,
transform: Matrix4.rotationZ(0.1),
child: Text('Rotated'),
)
4. 前景装饰(覆盖在 child 上)
less
Container(
decoration: BoxDecoration(color: Colors.green),
foregroundDecoration: BoxDecoration(
gradient: LinearGradient(colors: [Colors.black26, Colors.transparent]),
),
child: Image.asset('assets/pic.jpg', fit: BoxFit.cover),
)
性能建议(实践经验)
- 如果你只想要外观圆角但不需要裁剪子内容 ,优先使用
Container的decoration(BoxDecoration 中设置borderRadius)而不要设置clipBehavior。若子内容会溢出并必须裁剪,则使用ClipRRect或设置clipBehavior(注意性能)。 - 避免在列表(ListView/GridView)的每个 item 上使用复杂的阴影或
antiAliasWithSaveLayer。 - 使用
constraints明确限制尺寸能减少不必要的布局计算。 - 对于简单背景色使用
color比decoration更轻量(但别与 decoration 同时使用)。
速查表(Cheat Sheet)
| 属性 | 类型 | 用途速览 |
|---|---|---|
| key | Key? | 标识 Widget,列表重排时用 |
| alignment | AlignmentGeometry? | 子 Widget 在容器内的对齐方式 |
| padding | EdgeInsetsGeometry? | 内边距 |
| color | Color? | 背景色(不能与 decoration 同时使用) |
| decoration | Decoration? | 背景/边框/圆角/阴影等外观 |
| foregroundDecoration | Decoration? | 绘制在 child 之上的装饰 |
| width / height | double? | 固定宽/高 |
| constraints | BoxConstraints? | 更细粒度的尺寸约束 |
| margin | EdgeInsetsGeometry? | 外边距 |
| transform | Matrix4? | 变换(旋转/缩放/平移) |
| transformAlignment | AlignmentGeometry? | 变换的原点对齐 |
| clipBehavior | Clip | 裁剪策略(none/hardEdge/antiAlias/...) |
| child | Widget? | 容器内部的子 Widget |
Flutter BoxDecoration 属性详解(可一键复制版)
BoxDecoration 是用来描述盒子外观的核心类(通常与 Container(decoration: ...) 一起使用)。
它可以设置背景色、渐变、背景图、边框、圆角、阴影、混合模式等。下面逐项列出所有主要属性并给出详尽解释、使用注意与示例。
构造器(常见参数)
以下为常用参数签名(已按常见 API 汇总):
css
BoxDecoration({
Color? color,
DecorationImage? image,
BoxBorder? border,
BorderRadiusGeometry? borderRadius,
List<BoxShadow>? boxShadow,
Gradient? gradient,
BlendMode? backgroundBlendMode,
BoxShape shape = BoxShape.rectangle,
})
说明:
BoxDecoration的完整实现还包含 debug 用的字段/方法,但上面列出的就是在日常开发中实际会用到的核心属性。
属性总表(速览)
| 属性 | 类型 | 是否必需 | 作用简述 |
|---|---|---|---|
color |
Color? |
否 | 背景纯色 |
image |
DecorationImage? |
否 | 背景图片(完整配置项在 DecorationImage) |
border |
BoxBorder? |
否 | 边框(Border / BorderDirectional) |
borderRadius |
BorderRadiusGeometry? |
否 | 圆角(仅在 shape == BoxShape.rectangle 时生效) |
boxShadow |
List<BoxShadow>? |
否 | 阴影列表 |
gradient |
Gradient? |
否 | 背景渐变(线性、径向、扫线等) |
backgroundBlendMode |
BlendMode? |
否 | 背景颜色/渐变与 image 的混合模式 |
shape |
BoxShape |
否(默认 rectangle) | 形状(矩形或圆形) |
属性逐项详解
color --- Color?
- 作用:绘制纯色背景(最简单的背景方式)。
- 与
decoration.image/gradient的关系 :- 如果你同时使用
gradient和color,通常会以 gradient 为主 (实际渲染会依据backgroundBlendMode决定混合行为;在很多实现中 gradient 会覆盖 color,若需要组合可用backgroundBlendMode控制混合)。 - 如果你使用
image,color会与 image 一起绘制,且可通过backgroundBlendMode决定如何混合(例如将 color 作为遮色层)。
- 如果你同时使用
- 注意 :不要在同时传
decoration(如 BoxDecoration)内的color与Container的color外部字段冲突 ------ 在 Container 上一般使用decoration或color其一,否则会抛异常(Container 会检测并报错)。
image --- DecorationImage?
-
作用 :作为背景图绘制,类型为
DecorationImage,它包含很多子属性(如下列出)。 -
DecorationImage 常用字段(位于
DecorationImage内):image(ImageProvider):图片资源(AssetImage / NetworkImage / FileImage 等)fit(BoxFit):如何缩放/裁剪(cover / contain / fill / fitWidth / ...)alignment(Alignment):图片对齐方式repeat(ImageRepeat):是否重复centerSlice(Rect?):九宫拉伸裁切(用于可拉伸图)scale、matchTextDirection等
-
与
color/gradient的关系:- 背景图片绘制在 color/gradient 之上或与之混合,
backgroundBlendMode决定混合方式;若不需要混合,image 会覆盖底色(取决于 image 的透明度和 blendMode)。
- 背景图片绘制在 color/gradient 之上或与之混合,
-
示例(image 配置的伪写法):
BoxDecoration( image: DecorationImage( image: AssetImage('assets/bg.png'), fit: BoxFit.cover, alignment: Alignment.center, ), )
border --- BoxBorder?(例如 Border.all(...))
- 作用:为盒子绘制边框(可指定不同边的样式)。
- 常见构造 :
Border.all(color: Colors.grey, width: 1.0):统一边框Border(left: ..., right: ..., top: ..., bottom: ...):分别控制每条边
- 注意 :
- 当
shape == BoxShape.circle时,borderRadius会被忽略;border仍然可以用于圆形(会按圆形绘制边线)。 border与boxShadow的组合可能会在视觉上产生复杂效果(阴影绘制在外部,边框在盒子边缘)。
- 当
borderRadius --- BorderRadiusGeometry?
-
作用:为矩形盒子设置圆角(支持每个角不同半径)。
-
前提 :仅当
shape == BoxShape.rectangle时有效;若shape == BoxShape.circle,此属性会被忽略。 -
常见用法:
borderRadius: BorderRadius.circular(12)
或
css
borderRadius: BorderRadius.only(topLeft: Radius.circular(8), bottomRight: Radius.circular(16))
- 与
clip关系 :BoxDecoration本身不裁剪子内容;若你想裁剪子 Widget 超出圆角区域,需要在外面配合ClipRRect或在Container中设置clipBehavior(注意性能)。否则边角只是背景显示为圆角,但 child 可能溢出。
boxShadow --- List<BoxShadow>?
-
作用:在盒子外部绘制一个或多个阴影(可模拟浮起、立体效果)。
-
BoxShadow 字段:
color:阴影颜色offset:偏移(Offset(x, y))blurRadius:模糊半径spreadRadius:扩展半径(控制阴影大小)
-
示例:
boxShadow: [ BoxShadow(color: Colors.black26, blurRadius: 8, offset: Offset(0, 4)), ]
-
注意:阴影绘制涉及额外合成(可能触发 GPU 分层/SaveLayer),大量或复杂阴影会影响性能;在长滚动列表里谨慎使用。
gradient --- Gradient?
-
作用:用渐变填充背景(替代单一 color)。
-
支持类型 (均来自
dart:ui):LinearGradient(线性渐变)RadialGradient(径向渐变)SweepGradient(扫线渐变)
-
常见字段:
colors、stops、begin、end(线性)center、radius(径向)
-
示例:
gradient: LinearGradient( colors: [Colors.blue, Colors.purple], begin: Alignment.topLeft, end: Alignment.bottomRight, )
-
注意 :与
color的权责关系请参见color部分;如果同时设置 image,渐变与图片会根据backgroundBlendMode决定如何混合。
backgroundBlendMode --- BlendMode?
-
作用 :指定如何将
color/gradient与image混合(blend)。 -
示例:
backgroundBlendMode: BlendMode.overlay
-
常见场景:
- 使用
color作为"色彩遮罩"覆盖在图片上; - 将渐变叠加在图片上以形成特殊效果;
- 使用
-
注意:blend 运算可能会导致额外的绘制开销。
shape --- BoxShape(BoxShape.rectangle / BoxShape.circle)
-
作用:控制绘制的基本形状:矩形或圆形(circle)。
-
行为:
BoxShape.rectangle(默认),可配合borderRadius设置圆角。BoxShape.circle:忽略borderRadius,border 会以圆环形式绘制,image 会被限定到圆形区域(但不会自动裁剪 child,裁剪仍需 ClipRRect/ClipOval 或clipBehavior)。
-
示例(圆形头像):
BoxDecoration( shape: BoxShape.circle, image: DecorationImage(image: AssetImage('avatar.png'), fit: BoxFit.cover), )
交互规则与常见陷阱(重要)
-
color 与 decoration 的冲突 :在
Container场景下,不要同时使用Container(color: ...)与decoration: BoxDecoration(...)中的color,Container 会抛出异常。应把 color 放入 decoration 或只使用 Container.color。 -
borderRadius 与 shape 冲突 :如果
shape == BoxShape.circle,borderRadius将被忽略。确保用途匹配。 -
图片/渐变/颜色的绘制顺序与混合:
- 通常绘制顺序为:color(底色)→ gradient(若存在,通常覆盖底色或与之混合)→ image(将依据透明度/混合模式渲染在上面或与之混合)→ foreground(如有)。
- 使用
backgroundBlendMode可以改变 color/gradient 与 image 的混合方式。
-
BoxDecoration 不会自动裁剪子 Widget :若你需要同时限制 child 的可视区域(例如圆角内裁剪图片/子 Widget),需额外使用
ClipRRect/ClipOval或在Container上设置clipBehavior(并配合decoration的 shape/borderRadius)。裁剪会带来性能成本。 -
性能考量:
- 大量使用
boxShadow、blur、复杂DecorationImage(大图)或频繁改变gradient时,可能触发 GPU 重绘或 saveLayer,影响 FPS。 - 在滚动列表中尽量简化装饰,使用静态预渲染资源(如预合成图)或减少阴影/模糊频率。
- 大量使用
常用示例(缩进代码以便一键复制)
卡片式背景(圆角 + 阴影 + 边框)
less
Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(color: Colors.black26, blurRadius: 8, offset: Offset(0,4)),
],
border: Border.all(color: Colors.grey.shade200),
),
padding: EdgeInsets.all(16),
child: Text('Card content'),
)
渐变背景 + 背景图混合
less
Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.purple, Colors.blue],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
image: DecorationImage(
image: AssetImage('assets/pattern.png'),
fit: BoxFit.cover,
repeat: ImageRepeat.noRepeat,
),
backgroundBlendMode: BlendMode.overlay,
),
child: ...
)
圆形头像(背景图填充)
less
Container(
width: 80,
height: 80,
decoration: BoxDecoration(
shape: BoxShape.circle,
image: DecorationImage(
image: NetworkImage(avatarUrl),
fit: BoxFit.cover,
),
),
)
调试与最佳实践
-
使用 Flutter Inspector 查看实际绘制的装饰及边界。
-
当你只需要视觉上的圆角(不需裁剪子内容),优先使用
BoxDecoration.borderRadius而不要在外面再使用ClipRRect,这样可减少裁剪成本(但如果 child 会溢出,则必须裁剪)。 -
如果需要对背景执行复杂混合或滤镜,考虑预处理图片资源以降低实时渲染负担。
-
在 ListView 等大量重复元素中避免使用高成本的
boxShadow和 `antiAliasWithSaveLa
Flutter TextStyle 属性详解(可一键复制版)
TextStyle 是 Flutter 中定义文本外观的核心类(用于 Text、RichText、DefaultTextStyle 等)。下面把所有常用属性逐项列出并详细解释,包含使用提示、常见坑和示例。
构造器(简略)
下面是 TextStyle 构造器常见参数(不同 Flutter 版本可能会有细微差异):
arduino
const TextStyle({
bool inherit = true,
Color? color,
String? fontFamily,
List<String>? fontFamilyFallback,
double? fontSize,
FontWeight? fontWeight,
FontStyle? fontStyle,
double? letterSpacing,
double? wordSpacing,
double? height,
TextLeadingDistribution? leadingDistribution,
TextBaseline? textBaseline,
Locale? locale,
Paint? foreground,
Paint? background,
List<Shadow>? shadows,
List<FontFeature>? fontFeatures,
TextDecoration? decoration,
Color? decorationColor,
TextDecorationStyle? decorationStyle,
double? decorationThickness,
String? debugLabel,
String? package,
TextOverflow? overflow,
})
说明:上面列出的属性涵盖了 Flutter 官方
TextStyle(painting 库 / dart:ui)在常见版本中的核心字段。某些版本会新增小项(如更深入的 text trimming/overflow 控制),但核心概念一致。
属性详解(逐项)
inherit --- bool(默认 true)
- 含义 :是否从父
TextStyle(或DefaultTextStyle)继承缺失的属性。 - 用途 :通常保持
true(默认),只有在你想完整重置样式时才设为false。 - 示例 :若在
DefaultTextStyle下通过Text('x', style: TextStyle(inherit: false, color: Colors.red)),则只应用 color,不会继承其它父样式。
color --- Color?
-
含义:文本的填充颜色(最常用)。
-
注意 :如果同时设置了
foreground(Paint),foreground优先(它可以做描边/填充组合等更复杂效果)。 -
示例:
Text('Hello', style: TextStyle(color: Colors.blue));
fontFamily --- String?
-
含义 :首选字体族名称(例如
'Roboto')。 -
package :若字体在 package 中定义,需要在构造器中提供
package: 'package_name',构造器会自动把fontFamily前缀成packages/package_name/...。 -
示例:
Text('Hi', style: TextStyle(fontFamily: 'Raleway'));
fontFamilyFallback --- List<String>?
-
含义 :后备字体族列表。当
fontFamily中没有某个字形时,按顺序在这些字体中寻找。 -
用途:跨语言或 emoji 支持时很有用。
-
示例:
TextStyle(fontFamily: 'MyFont', fontFamilyFallback: ['NotoSans', 'sans-serif']);
fontSize --- double?
-
含义:字体大小(逻辑像素)。
-
提示 :若同时设置
height,行高是基于fontSize的倍数。 -
示例:
TextStyle(fontSize: 18);
fontWeight --- FontWeight?
-
含义 :字体粗细(例如
FontWeight.w400/FontWeight.bold)。 -
示例:
TextStyle(fontWeight: FontWeight.bold);
fontStyle --- FontStyle?
-
含义 :字体风格,通常为
FontStyle.normal或FontStyle.italic。 -
示例:
TextStyle(fontStyle: FontStyle.italic);
letterSpacing --- double?
-
含义:字母间距(每个字形间的额外空白,单位逻辑像素)。可为负值。
-
示例:
TextStyle(letterSpacing: 1.2);
wordSpacing --- double?
-
含义:单词之间的额外间距(单位逻辑像素)。
-
示例:
TextStyle(wordSpacing: 2.0);
height --- double?
-
含义 :行高倍率(将
fontSize * height作为行高)。如果为null,则使用字体自身的度量(font metrics)。 -
注意 :
height是整体行高(包括 ascent 和 descent),并非仅上下间距。 -
示例:
TextStyle(fontSize: 16, height: 1.5);
leadingDistribution --- TextLeadingDistribution?
- 含义 :控制行间 leading(行高中空白)如何分配到行上方与下方(
proportional或even)。 - 用途:细化多行文本的垂直对齐感受,特别是当你混合不同字体尺寸时。
textBaseline --- TextBaseline?
- 含义 :用于
crossAxisAlignment: CrossAxisAlignment.baseline等基线对齐场景,通常选TextBaseline.alphabetic或TextBaseline.ideographic。 - 注意:仅在需要基线对齐时使用,否则可忽略。
locale --- Locale?
-
含义:告诉绘制层应使用哪个区域(语言)来选择变体(例如某些字体的语言替换)。
-
示例:
TextStyle(locale: Locale('ja'));
foreground --- Paint?
-
含义 :直接为文本提供
Paint,用来绘制文本(支持描边、渐变着色、混合模式等高级效果)。 -
优先级 :若
foreground非空,它会覆盖color。 -
示例(描边):
final paint = Paint() ..style = PaintingStyle.stroke ..strokeWidth = 1.5 ..color = Colors.black; TextStyle(foreground: paint);
background --- Paint?
- 含义 :用
Paint绘制文本背景(不是backgroundColor)。可创建复杂的背景效果(渐变、图案)。 - 注意 :与
backgroundColor(更常用的简单背景)不同,background是低级Paint。
shadows --- List<Shadow>?
-
含义 :文字阴影列表(可以多个)。每个
Shadow包含color、offset、blurRadius。 -
示例:
TextStyle(shadows: [Shadow(color: Colors.black26, offset: Offset(1,1), blurRadius: 2)]);
fontFeatures --- List<FontFeature>?
-
含义:字体特性,用于选择字体提供的特定 OpenType 功能(比如 tabular numbers、oldstyle figures、liga 等)。
-
示例:
TextStyle(fontFeatures: [FontFeature.tabularFigures()]);
decoration --- TextDecoration?
-
含义 :文本修饰(如下划线
TextDecoration.underline、删除线TextDecoration.lineThrough、上划线)。 -
示例:
TextStyle(decoration: TextDecoration.underline);
decorationColor --- Color?
-
含义 :修饰线(下划线等)的颜色(若未设置则通常使用
color)。 -
示例:
TextStyle(decoration: TextDecoration.underline, decorationColor: Colors.red);
decorationStyle --- TextDecorationStyle?
-
含义 :修饰线的样式(如
solid、double、dashed、dotted、wavy)。 -
示例:
TextStyle(decoration: TextDecoration.underline, decorationStyle: TextDecorationStyle.wavy);
decorationThickness --- double?
-
含义:修饰线粗细(乘以字体的默认线厚比例),可精确控制下划线/删除线粗细。
-
示例:
TextStyle(decoration: TextDecoration.underline, decorationThickness: 2.0);
debugLabel --- String?
- 含义:仅用于调试/诊断信息的标签(不会影响渲染),Flutter 工具/日志可能会显示它来帮助识别样式来源。
- 示例 :开发时可加上
debugLabel: 'headline-override'。
package --- String?(构造器参数)
-
含义 :当
fontFamily指向一个在 package 中声明的字体时,需要通过构造器传入package: 'my_package',以便正确前缀资源路径。 -
示例(声明 fontFamily 在 package 中):
const TextStyle(fontFamily: 'MyFont', package: 'my_package');
fontFeatures(已在上面)与 fontFamilyFallback(已在上面)
- 再次提示:
fontFamilyFallback对于 emoji、多语言渲染非常有用;fontFeatures让你启用 OpenType 功能。
overflow --- TextOverflow?(较新的属性)
- 含义 :告诉
TextPainter在文本修建/测量时如何处理溢出(例如TextOverflow.visible/ellipsis/clip)。 - 用途 :当需要对富文本进行特殊截断行为时可用(注意:
Text小部件也有自己的overflow参数,TextStyle.overflow是更基础的绘制层控制)。
使用优先级提示(常见坑)
foreground优先于color:如果你设置了foreground(Paint),它会替代color的填充行为。backgroundvsbackgroundColor:background接受Paint,可以实现更复杂效果;若只需单色背景,考虑把背景放在容器上或使用backgroundColor(在某些 API/版本中可用)。- 继承 (
inherit) :很多时候你只想覆盖部分属性,保持inherit: true让其它样式从父节点继承。 - 字体加载/包(package) :使用第三方包里的字体需要构造器
package参数或在pubspec.yaml正确声明。 - 性能 :
shadows、foreground(描边)、复杂fontFeatures在大量文本或频繁重绘时会有性能影响。尽量在需要时使用,避免在长列表里反复使用高开销样式。
常见示例(缩进写法,便于一键复制)
基本样式
less
TextStyle(
color: Colors.black87,
fontSize: 16,
fontWeight: FontWeight.w500,
)
描边 + 填充(使用 foreground + background)
ini
final stroke = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 2
..color = Colors.black;
final fill = Paint()
..style = PaintingStyle.fill
..color = Colors.white;
TextStyle(
foreground: stroke, // 描边
background: fill, // 背景填充(高级用法)
)
阴影 + 下划线
less
TextStyle(
color: Colors.blue,
decoration: TextDecoration.underline,
decorationColor: Colors.blueAccent,
decorationStyle: TextDecorationStyle.dashed,
shadows: [
Shadow(color: Colors.black26, offset: Offset(1,1), blurRadius: 2),
],
)
字体特性(表格数字)
less
TextStyle(
fontFeatures: [FontFeature.tabularFigures()],
fontFamily: 'RobotoMono',
fontSize: 14,
)
多语言回退字体
less
TextStyle(
fontFamily: 'PrimaryFont',
fontFamilyFallback: ['NotoSans', 'Segoe UI Emoji'],
)
调试建议
- 使用
debugLabel帮助在 DevTools / 日志里定位样式来源。 - 在遇到"样式没有生效"时,检查
inherit、foreground、DefaultTextStyle覆盖规则以及父级TextSpan的样式继承链。 - 使用 Flutter Inspector 查看最终合并后的
TextStyle(Text-> properties -> style)。
简短速查表(Cheat Sheet)
| 属性 | 类型 | 用途 |
|---|---|---|
| inherit | bool | 是否继承父样式 |
| color | Color? | 文本颜色(常用) |
| fontFamily | String? | 字体族 |
| fontFamilyFallback | List? | 回退字体列表 |
| fontSize | double? | 字体大小 |
| fontWeight | FontWeight? | 粗细 |
| fontStyle | FontStyle? | normal / italic |
| letterSpacing | double? | 字母间距 |
| wordSpacing | double? | 单词间距 |
| height | double? | 行高倍数 |
| leadingDistribution | TextLeadingDistribution? | leading 分配策略 |
| textBaseline | TextBaseline? | 基线类型(alphabetic/ideographic) |
| locale | Locale? | 文本区域(语言) |
| foreground | Paint? | 前景 Paint(高级) |
| background | Paint? | 背景 Paint(高级) |
| shadows | List? | 阴影列表 |
| fontFeatures | List? | OpenType 特性 |
| decoration | TextDecoration? | 下划线/删除线等 |
| decorationColor | Color? | 修饰线颜色 |
| decorationStyle | TextDecorationStyle? | 修饰线样式 |
| decorationThickness | double? | 修饰线粗细 |
| debugLabel | String? | 调试标签 |
| package | String? | 若字体在 package 中,传 package 名称 |
| overflow | TextOverflow? | 文本溢出绘制策略(底层) |