Flutter Widget 完全指南
目录
- 基础Widget详解
- 布局Widget详解
- 容器Widget详解
- 滚动Widget详解
- 按钮Widget详解
- 输入Widget详解
- 对话框Widget详解
- 动画Widget详解
- 导航Widget详解
- 状态管理Widget详解
- 高级Widget详解
- 性能优化Widget详解
基础Widget详解
Text Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| data | String | 要显示的文本内容 | "Hello World" |
| style | TextStyle | 文本样式 | TextStyle(fontSize: 16) |
| textAlign | TextAlign | 文本对齐方式 | TextAlign.center |
| maxLines | int | 最大显示行数 | 2 |
| overflow | TextOverflow | 文本溢出处理方式 | TextOverflow.ellipsis |
| textDirection | TextDirection | 文本方向 | TextDirection.ltr |
| softWrap | bool | 是否自动换行 | true |
| textScaleFactor | double | 文本缩放因子 | 1.5 |
| semanticsLabel | String | 语义标签 | "标题" |
使用示例:
dart
Text(
'Hello Flutter',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.blue,
),
textAlign: TextAlign.center,
maxLines: 2,
overflow: TextOverflow.ellipsis,
)
Image Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| image | ImageProvider | 图片源 | AssetImage('assets/image.png') |
| width | double | 宽度 | 200.0 |
| height | double | 高度 | 200.0 |
| fit | BoxFit | 填充方式 | BoxFit.cover |
| alignment | AlignmentGeometry | 对齐方式 | Alignment.center |
| repeat | ImageRepeat | 重复方式 | ImageRepeat.noRepeat |
| color | Color | 混合颜色 | Colors.blue.withOpacity(0.5) |
| colorBlendMode | BlendMode | 混合模式 | BlendMode.srcIn |
| filterQuality | FilterQuality | 滤镜质量 | FilterQuality.high |
图片源类型:
dart
// 网络图片
Image.network('https://example.com/image.png')
// 本地资源图片
Image.asset('assets/image.png')
// 文件图片
Image.file(File('/path/to/image.png'))
// 内存图片
Image.memory(Uint8List bytes)
// 使用ImageProvider
Image(image: AssetImage('assets/image.png'))
Icon Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| icon | IconData | 图标数据 | Icons.home |
| size | double | 图标大小 | 24.0 |
| color | Color | 图标颜色 | Colors.blue |
| semanticLabel | String | 语义标签 | "首页" |
| textDirection | TextDirection | 文本方向 | TextDirection.ltr |
使用示例:
dart
Icon(
Icons.star,
size: 32,
color: Colors.amber,
)
RichText Widget
| 属性 | 类型 | 说明 |
|---|---|---|
| text | TextSpan | 文本内容 |
| textAlign | TextAlign | 对齐方式 |
| textDirection | TextDirection | 文本方向 |
| softWrap | bool | 是否自动换行 |
| overflow | TextOverflow | 溢出处理 |
| maxLines | int | 最大行数 |
使用示例:
dart
RichText(
text: TextSpan(
style: DefaultTextStyle.of(context).style,
children: <TextSpan>[
TextSpan(text: 'Hello ', style: TextStyle(fontWeight: FontWeight.bold)),
TextSpan(
text: 'world',
style: TextStyle(color: Colors.blue),
),
],
),
)
布局Widget详解
Row Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| children | List | 子Widget列表 | [Text('A'), Text('B')] |
| mainAxisAlignment | MainAxisAlignment | 主轴对齐方式 | MainAxisAlignment.spaceBetween |
| crossAxisAlignment | CrossAxisAlignment | 交叉轴对齐方式 | CrossAxisAlignment.center |
| mainAxisSize | MainAxisSize | 主轴大小 | MainAxisSize.max |
| textDirection | TextDirection | 文本方向 | TextDirection.ltr |
| verticalDirection | VerticalDirection | 垂直方向 | VerticalDirection.down |
| textBaseline | TextBaseline | 文本基线 | TextBaseline.alphabetic |
使用示例:
dart
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(Icons.menu),
Expanded(child: Text('标题', textAlign: TextAlign.center)),
Icon(Icons.search),
],
)
Column Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| children | List | 子Widget列表 | [Text('A'), Text('B')] |
| mainAxisAlignment | MainAxisAlignment | 主轴对齐方式 | MainAxisAlignment.spaceBetween |
| crossAxisAlignment | CrossAxisAlignment | 交叉轴对齐方式 | CrossAxisAlignment.center |
| mainAxisSize | MainAxisSize | 主轴大小 | MainAxisSize.max |
| textDirection | TextDirection | 文本方向 | TextDirection.ltr |
| verticalDirection | VerticalDirection | 垂直方向 | VerticalDirection.down |
使用示例:
dart
Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text('第一行'),
Text('第二行'),
Text('第三行'),
],
)
Stack Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| children | List | 子Widget列表 | [Text('A'), Text('B')] |
| alignment | AlignmentGeometry | 对齐方式 | Alignment.center |
| textDirection | TextDirection | 文本方向 | TextDirection.ltr |
| fit | StackFit | 堆叠适配方式 | StackFit.loose |
| clipBehavior | Clip | 裁剪行为 | Clip.hardEdge |
使用示例:
dart
Stack(
alignment: Alignment.center,
children: [
Image.network('https://example.com/bg.jpg'),
Text(
'居中文字',
style: TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
],
)
GridView Widget
构造函数类型:
GridView.count- 固定列数GridView.extent- 固定最大宽度GridView.builder- 动态构建
常用属性:
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| gridDelegate | SliverGridDelegate | 网格代理 | SliverGridDelegateWithFixedCrossAxisCount |
| children | List | 子Widget列表 | [Container(), Container()] |
| scrollDirection | Axis | 滚动方向 | Axis.vertical |
| reverse | bool | 是否反向滚动 | false |
| controller | ScrollController | 滚动控制器 | ScrollController() |
| primary | bool | 是否为主滚动视图 | true |
| physics | ScrollPhysics | 滚动物理特性 | BouncingScrollPhysics() |
| shrinkWrap | bool | 是否根据内容收缩 | false |
| padding | EdgeInsetsGeometry | 内边距 | EdgeInsets.all(10) |
使用示例:
dart
GridView.count(
crossAxisCount: 2,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
padding: EdgeInsets.all(10),
children: List.generate(20, (index) {
return Container(
color: Colors.primaries[index % Colors.primaries.length],
child: Center(child: Text('$index')),
);
}),
)
ListView Widget
构造函数类型:
ListView- 固定子Widget列表ListView.builder- 按需构建子WidgetListView.separated- 带分隔符的列表ListView.custom- 自定义子Widget构建
常用属性:
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| children | List | 子Widget列表 | [Text('A'), Text('B')] |
| itemCount | int | 子项数量 | 100 |
| itemBuilder | ItemBuilder | 子项构建器 | (context, index) => Text('$index') |
| separatorBuilder | IndexedWidgetBuilder | 分隔符构建器 | (context, index) => Divider() |
| scrollDirection | Axis | 滚动方向 | Axis.vertical |
| reverse | bool | 是否反向滚动 | false |
| controller | ScrollController | 滚动控制器 | ScrollController() |
| primary | bool | 是否为主滚动视图 | true |
| physics | ScrollPhysics | 滚动物理特性 | BouncingScrollPhysics() |
| shrinkWrap | bool | 是否根据内容收缩 | false |
| padding | EdgeInsetsGeometry | 内边距 | EdgeInsets.all(10) |
| itemExtent | double | 子项固定高度 | 50.0 |
使用示例:
dart
ListView.builder(
itemCount: 100,
itemExtent: 50,
padding: EdgeInsets.symmetric(vertical: 10),
itemBuilder: (context, index) {
return ListTile(
title: Text('Item $index'),
leading: Icon(Icons.list),
);
},
)
Expanded Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| flex | int | 弹性系数 | 1 |
| child | Widget | 子Widget | Text('内容') |
使用示例:
dart
Row(
children: [
Expanded(
flex: 2,
child: Container(color: Colors.red),
),
Expanded(
flex: 1,
child: Container(color: Colors.blue),
),
],
)
Flexible Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| flex | int | 弹性系数 | 1 |
| fit | FlexFit | 适配方式 | FlexFit.loose |
| child | Widget | 子Widget | Text('内容') |
使用示例:
dart
Row(
children: [
Flexible(
child: Container(
width: 200,
color: Colors.red,
),
),
Flexible(
child: Container(
width: 100,
color: Colors.blue,
),
),
],
)
Wrap Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| children | List | 子Widget列表 | [Text('A'), Text('B')] |
| direction | Axis | 主轴方向 | Axis.horizontal |
| alignment | WrapAlignment | 主轴对齐方式 | WrapAlignment.start |
| spacing | double | 主轴间距 | 10.0 |
| runAlignment | WrapAlignment | 交叉轴对齐方式 | WrapAlignment.start |
| runSpacing | double | 交叉轴间距 | 10.0 |
| crossAxisAlignment | WrapCrossAlignment | 交叉轴对齐 | WrapCrossAlignment.start |
| textDirection | TextDirection | 文本方向 | TextDirection.ltr |
| verticalDirection | VerticalDirection | 垂直方向 | VerticalDirection.down |
使用示例:
dart
Wrap(
spacing: 10,
runSpacing: 10,
children: List.generate(10, (index) {
return Chip(
label: Text('Tag $index'),
avatar: CircleAvatar(child: Text('$index')),
);
}),
)
容器Widget详解
Container Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| alignment | AlignmentGeometry | 子Widget对齐 | Alignment.center |
| padding | EdgeInsetsGeometry | 内边距 | EdgeInsets.all(10) |
| color | Color | 背景色 | Colors.blue |
| decoration | BoxDecoration | 装饰 | BoxDecoration(...) |
| foregroundDecoration | BoxDecoration | 前景装饰 | BoxDecoration(...) |
| width | double | 宽度 | 200.0 |
| height | double | 高度 | 100.0 |
| constraints | BoxConstraints | 尺寸约束 | BoxConstraints(...) |
| margin | EdgeInsetsGeometry | 外边距 | EdgeInsets.all(10) |
| transform | Matrix4 | 变换矩阵 | Matrix4.rotationZ(0.1) |
| child | Widget | 子Widget | Text('内容') |
使用示例:
dart
Container(
padding: EdgeInsets.all(16),
margin: EdgeInsets.symmetric(horizontal: 20),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.blue, Colors.purple],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Colors.black26,
blurRadius: 8,
offset: Offset(0, 4),
),
],
),
child: Text('装饰容器'),
)
Padding Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| padding | EdgeInsetsGeometry | 内边距 | EdgeInsets.all(10) |
| child | Widget | 子Widget | Text('内容') |
使用示例:
dart
Padding(
padding: EdgeInsets.all(16),
child: Text('带内边距的文本'),
)
Center Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| widthFactor | double | 宽度因子 | 1.0 |
| heightFactor | double | 高度因子 | 1.0 |
| child | Widget | 子Widget | Text('内容') |
使用示例:
dart
Center(
child: Text('居中文本'),
)
Align Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| alignment | AlignmentGeometry | 对齐方式 | Alignment.topRight |
| widthFactor | double | 宽度因子 | 1.0 |
| heightFactor | double | 高度因子 | 1.0 |
| child | Widget | 子Widget | Text('内容') |
使用示例:
dart
Align(
alignment: Alignment.topRight,
child: Text('右上角文本'),
)
SizedBox Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| width | double | 宽度 | 100.0 |
| height | double | 高度 | 50.0 |
| child | Widget | 子Widget | Text('内容') |
使用示例:
dart
// 固定大小
SizedBox(
width: 100,
height: 100,
child: Text('固定大小'),
)
// 占位空间
SizedBox(height: 20)
AspectRatio Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| aspectRatio | double | 宽高比 | 16/9 |
| child | Widget | 子Widget | Image.asset(...) |
使用示例:
dart
AspectRatio(
aspectRatio: 16 / 9,
child: Image.asset('assets/image.jpg'),
)
ConstrainedBox Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| constraints | BoxConstraints | 尺寸约束 | BoxConstraints(...) |
| child | Widget | 子Widget | Text('内容') |
使用示例:
dart
ConstrainedBox(
constraints: BoxConstraints(
minWidth: 100,
maxWidth: 200,
minHeight: 50,
maxHeight: 100,
),
child: Text('约束文本'),
)
Transform Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| transform | Matrix4 | 变换矩阵 | Matrix4.rotationZ(0.5) |
| origin | Offset | 变换原点 | Offset(50, 50) |
| alignment | AlignmentGeometry | 对齐方式 | Alignment.center |
| transformHitTests | bool | 是否变换点击测试 | true |
| child | Widget | 子Widget | Text('内容') |
使用示例:
dart
Transform.rotate(
angle: 0.5,
child: Text('旋转文本'),
)
ClipRect Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| child | Widget | 子Widget | Image.asset(...) |
| clipBehavior | Clip | 裁剪行为 | Clip.hardEdge |
使用示例:
dart
ClipRect(
child: Align(
alignment: Alignment.topCenter,
heightFactor: 0.5,
child: Image.asset('assets/image.jpg'),
),
)
ClipRRect Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| borderRadius | BorderRadius | 圆角半径 | BorderRadius.circular(10) |
| child | Widget | 子Widget | Image.asset(...) |
| clipBehavior | Clip | 裁剪行为 | Clip.antiAlias |
使用示例:
dart
ClipRRect(
borderRadius: BorderRadius.circular(12),
child: Image.asset('assets/image.jpg'),
)
ClipOval Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| child | Widget | 子Widget | Image.asset(...) |
| clipBehavior | Clip | 裁剪行为 | Clip.antiAlias |
使用示例:
dart
ClipOval(
child: Image.asset('assets/avatar.jpg'),
)
滚动Widget详解
SingleChildScrollView Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| scrollDirection | Axis | 滚动方向 | Axis.vertical |
| reverse | bool | 是否反向滚动 | false |
| padding | EdgeInsetsGeometry | 内边距 | EdgeInsets.all(10) |
| primary | bool | 是否为主滚动视图 | true |
| physics | ScrollPhysics | 滚动物理特性 | BouncingScrollPhysics() |
| controller | ScrollController | 滚动控制器 | ScrollController() |
| child | Widget | 子Widget | Column(...) |
| dragStartBehavior | DragStartBehavior | 拖动开始行为 | DragStartBehavior.start |
| clipBehavior | Clip | 裁剪行为 | Clip.hardEdge |
| restorationId | String | 恢复ID | 'scroll_view' |
使用示例:
dart
SingleChildScrollView(
padding: EdgeInsets.all(16),
child: Column(
children: List.generate(20, (index) {
return Padding(
padding: EdgeInsets.only(bottom: 10),
child: Text('Item $index'),
);
}),
),
)
CustomScrollView Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| slivers | List | Sliver列表 | [SliverAppBar(), SliverList()] |
| scrollDirection | Axis | 滚动方向 | Axis.vertical |
| reverse | bool | 是否反向滚动 | false |
| controller | ScrollController | 滚动控制器 | ScrollController() |
| primary | bool | 是否为主滚动视图 | true |
| physics | ScrollPhysics | 滚动物理特性 | BouncingScrollPhysics() |
| shrinkWrap | bool | 是否根据内容收缩 | false |
| anchor | double | 滚动锚点 | 0.0 |
| cacheExtent | double | 缓存范围 | 250.0 |
| dragStartBehavior | DragStartBehavior | 拖动开始行为 | DragStartBehavior.start |
| clipBehavior | Clip | 裁剪行为 | Clip.hardEdge |
| restorationId | String | 恢复ID | 'custom_scroll' |
使用示例:
dart
CustomScrollView(
slivers: [
SliverAppBar(
expandedHeight: 200,
floating: true,
pinned: true,
flexibleSpace: FlexibleSpaceBar(
title: Text('CustomScrollView'),
),
),
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) => ListTile(title: Text('Item $index')),
childCount: 20,
),
),
],
)
PageView Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| children | List | 子Widget列表 | [Page1(), Page2()] |
| scrollDirection | Axis | 滚动方向 | Axis.horizontal |
| reverse | bool | 是否反向滚动 | false |
| controller | PageController | 页面控制器 | PageController() |
| physics | ScrollPhysics | 滚动物理特性 | BouncingScrollPhysics() |
| pageSnapping | bool | 是否启用页面吸附 | true |
| onPageChanged | ValueChanged | 页面改变回调 | (index) {} |
| allowImplicitScrolling | bool | 是否允许隐式滚动 | false |
| clipBehavior | Clip | 裁剪行为 | Clip.hardEdge |
| restorationId | String | 恢复ID | 'page_view' |
使用示例:
dart
PageView.builder(
itemCount: 5,
onPageChanged: (index) {
print('当前页面: $index');
},
itemBuilder: (context, index) {
return Container(
color: Colors.primaries[index % Colors.primaries.length],
child: Center(
child: Text(
'Page $index',
style: TextStyle(fontSize: 32, color: Colors.white),
),
),
);
},
)
RefreshIndicator Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| onRefresh | Future Function() | 刷新回调 | () async {} |
| child | ScrollableWidget | 可滚动子Widget | ListView() |
| color | Color | 指示器颜色 | Colors.blue |
| backgroundColor | Color | 背景颜色 | Colors.white |
| displacement | double | 指示器位移 | 40.0 |
| edgeOffset | double | 边缘偏移 | 0.0 |
| notificationPredicate | ScrollNotificationPredicate | 通知谓词 | defaultScrollNotificationPredicate |
| semanticsLabel | String | 语义标签 | "刷新" |
| semanticsValue | String | 语义值 | "刷新中" |
使用示例:
dart
RefreshIndicator(
onRefresh: () async {
await Future.delayed(Duration(seconds: 2));
},
child: ListView.builder(
itemCount: 20,
itemBuilder: (context, index) {
return ListTile(title: Text('Item $index'));
},
),
)
按钮Widget详解
ElevatedButton Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| onPressed | VoidCallback | 点击回调 | () {} |
| onLongPress | VoidCallback | 长按回调 | () {} |
| style | ButtonStyle | 按钮样式 | ElevatedButton.styleFrom(...) |
| focusNode | FocusNode | 焦点节点 | FocusNode() |
| autofocus | bool | 是否自动获取焦点 | false |
| clipBehavior | Clip | 裁剪行为 | Clip.none |
| child | Widget | 子Widget | Text('按钮') |
使用示例:
dart
ElevatedButton(
onPressed: () {
print('按钮被点击');
},
style: ElevatedButton.styleFrom(
primary: Colors.blue,
onPrimary: Colors.white,
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 15),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
child: Text('提交'),
)
TextButton Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| onPressed | VoidCallback | 点击回调 | () {} |
| onLongPress | VoidCallback | 长按回调 | () {} |
| style | ButtonStyle | 按钮样式 | TextButton.styleFrom(...) |
| focusNode | FocusNode | 焦点节点 | FocusNode() |
| autofocus | bool | 是否自动获取焦点 | false |
| clipBehavior | Clip | 裁剪行为 | Clip.none |
| child | Widget | 子Widget | Text('按钮') |
使用示例:
dart
TextButton(
onPressed: () {
print('文本按钮被点击');
},
style: TextButton.styleFrom(
primary: Colors.blue,
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
),
child: Text('取消'),
)
OutlinedButton Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| onPressed | VoidCallback | 点击回调 | () {} |
| onLongPress | VoidCallback | 长按回调 | () {} |
| style | ButtonStyle | 按钮样式 | OutlinedButton.styleFrom(...) |
| focusNode | FocusNode | 焦点节点 | FocusNode() |
| autofocus | bool | 是否自动获取焦点 | false |
| clipBehavior | Clip | 裁剪行为 | Clip.none |
| child | Widget | 子Widget | Text('按钮') |
使用示例:
dart
OutlinedButton(
onPressed: () {
print('描边按钮被点击');
},
style: OutlinedButton.styleFrom(
primary: Colors.blue,
side: BorderSide(color: Colors.blue, width: 2),
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 15),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
child: Text('详情'),
)
IconButton Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| icon | Widget | 图标 | Icon(Icons.home) |
| onPressed | VoidCallback | 点击回调 | () {} |
| iconSize | double | 图标大小 | 24.0 |
| color | Color | 图标颜色 | Colors.blue |
| splashColor | Color | 水波纹颜色 | Colors.blue.withOpacity(0.3) |
| highlightColor | Color | 高亮颜色 | Colors.blue.withOpacity(0.1) |
| focusColor | Color | 焦点颜色 | Colors.blue.withOpacity(0.1) |
| hoverColor | Color | 悬停颜色 | Colors.blue.withOpacity(0.1) |
| focusNode | FocusNode | 焦点节点 | FocusNode() |
| autofocus | bool | 是否自动获取焦点 | false |
| tooltip | String | 工具提示 | "首页" |
| alignment | AlignmentGeometry | 对齐方式 | Alignment.center |
| padding | EdgeInsetsGeometry | 内边距 | EdgeInsets.all(8) |
| constraints | BoxConstraints | 尺寸约束 | BoxConstraints(...) |
| splashRadius | double | 水波纹半径 | 20.0 |
使用示例:
dart
IconButton(
icon: Icon(Icons.favorite),
color: Colors.red,
iconSize: 32,
onPressed: () {
print('收藏按钮被点击');
},
tooltip: '收藏',
)
FloatingActionButton Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| onPressed | VoidCallback | 点击回调 | () {} |
| child | Widget | 子Widget | Icon(Icons.add) |
| tooltip | String | 工具提示 | "添加" |
| foregroundColor | Color | 前景色 | Colors.white |
| backgroundColor | Color | 背景色 | Colors.blue |
| focusColor | Color | 焦点颜色 | Colors.blue.withOpacity(0.1) |
| hoverColor | Color | 悬停颜色 | Colors.blue.withOpacity(0.1) |
| splashColor | Color | 水波纹颜色 | Colors.blue.withOpacity(0.3) |
| elevation | double | 阴影高度 | 6.0 |
| focusElevation | double | 焦点阴影高度 | 8.0 |
| hoverElevation | double | 悬停阴影高度 | 8.0 |
| highlightElevation | double | 高亮阴影高度 | 12.0 |
| disabledElevation | double | 禁用阴影高度 | 0.0 |
| mini | bool | 是否为小尺寸 | false |
| shape | ShapeBorder | 形状 | CircleBorder() |
| clipBehavior | Clip | 裁剪行为 | Clip.none |
| focusNode | FocusNode | 焦点节点 | FocusNode() |
| autofocus | bool | 是否自动获取焦点 | false |
| isExtended | bool | 是否为扩展型 | false |
| materialTapTargetSize | MaterialTapTargetSize | 点击目标大小 | MaterialTapTargetSize.padded |
使用示例:
dart
FloatingActionButton(
onPressed: () {
print('添加按钮被点击');
},
child: Icon(Icons.add),
backgroundColor: Colors.blue,
tooltip: '添加',
)
InkWell Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| onTap | VoidCallback | 点击回调 | () {} |
| onDoubleTap | VoidCallback | 双击回调 | () {} |
| onLongPress | VoidCallback | 长按回调 | () {} |
| onTapDown | GestureTapDownCallback | 按下回调 | (details) {} |
| onTapUp | GestureTapUpCallback | 抬起回调 | (details) {} |
| onTapCancel | GestureTapCancelCallback | 取消回调 | () {} |
| child | Widget | 子Widget | Container(...) |
| splashColor | Color | 水波纹颜色 | Colors.blue.withOpacity(0.3) |
| highlightColor | Color | 高亮颜色 | Colors.blue.withOpacity(0.1) |
| focusColor | Color | 焦点颜色 | Colors.blue.withOpacity(0.1) |
| hoverColor | Color | 悬停颜色 | Colors.blue.withOpacity(0.1) |
| focusNode | FocusNode | 焦点节点 | FocusNode() |
| canRequestFocus | bool | 是否可以请求焦点 | true |
| borderRadius | BorderRadius | 圆角半径 | BorderRadius.circular(8) |
| customBorder | ShapeBorder | 自定义边框 | RoundedRectangleBorder(...) |
| enableFeedback | bool | 是否启用反馈 | true |
| excludeFromSemantics | bool | 是否排除语义 | false |
| radius | double | 水波纹半径 | null |
使用示例:
dart
InkWell(
onTap: () {
print('容器被点击');
},
splashColor: Colors.blue.withOpacity(0.3),
borderRadius: BorderRadius.circular(12),
child: Container(
padding: EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(12),
),
child: Text('可点击容器'),
),
)
GestureDetector Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| onTap | VoidCallback | 点击回调 | () {} |
| onTapDown | GestureTapDownCallback | 按下回调 | (details) {} |
| onTapUp | GestureTapUpCallback | 抬起回调 | (details) {} |
| onTapCancel | GestureTapCancelCallback | 取消回调 | () {} |
| onDoubleTap | VoidCallback | 双击回调 | () {} |
| onLongPress | VoidCallback | 长按回调 | () {} |
| onLongPressStart | GestureLongPressStartCallback | 长按开始回调 | (details) {} |
| onLongPressMoveUpdate | GestureLongPressMoveUpdateCallback | 长按移动回调 | (details) {} |
| onLongPressUp | GestureLongPressUpCallback | 长按抬起回调 | () {} |
| onLongPressEnd | GestureLongPressEndCallback | 长按结束回调 | (details) {} |
| onVerticalDragStart | GestureDragStartCallback | 垂直拖动开始 | (details) {} |
| onVerticalDragUpdate | GestureDragUpdateCallback | 垂直拖动更新 | (details) {} |
| onVerticalDragEnd | GestureDragEndCallback | 垂直拖动结束 | (details) {} |
| onHorizontalDragStart | GestureDragStartCallback | 水平拖动开始 | (details) {} |
| onHorizontalDragUpdate | GestureDragUpdateCallback | 水平拖动更新 | (details) {} |
| onHorizontalDragEnd | GestureDragEndCallback | 水平拖动结束 | (details) {} |
| onPanStart | GestureDragStartCallback | 平移开始 | (details) {} |
| onPanUpdate | GestureDragUpdateCallback | 平移更新 | (details) {} |
| onPanEnd | GestureDragEndCallback | 平移结束 | (details) {} |
| onScaleStart | GestureScaleStartCallback | 缩放开始 | (details) {} |
| onScaleUpdate | GestureScaleUpdateCallback | 缩放更新 | (details) {} |
| onScaleEnd | GestureScaleEndCallback | 缩放结束 | (details) {} |
| child | Widget | 子Widget | Container(...) |
| behavior | HitTestBehavior | 点击测试行为 | HitTestBehavior.opaque |
使用示例:
dart
GestureDetector(
onTap: () {
print('点击');
},
onDoubleTap: () {
print('双击');
},
onLongPress: () {
print('长按');
},
onPanUpdate: (details) {
print('平移: ${details.delta}');
},
child: Container(
width: 200,
height: 200,
color: Colors.blue,
child: Center(child: Text('手势区域')),
),
)
输入Widget详解
TextField Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| controller | TextEditingController | 文本控制器 | TextEditingController() |
| focusNode | FocusNode | 焦点节点 | FocusNode() |
| decoration | InputDecoration | 装饰 | InputDecoration(...) |
| keyboardType | TextInputType | 键盘类型 | TextInputType.text |
| textInputAction | TextInputAction | 键盘动作 | TextInputAction.done |
| style | TextStyle | 文本样式 | TextStyle(fontSize: 16) |
| textAlign | TextAlign | 文本对齐 | TextAlign.start |
| autofocus | bool | 是否自动聚焦 | false |
| obscureText | bool | 是否隐藏文本 | false |
| maxLines | int | 最大行数 | 1 |
| minLines | int | 最小行数 | null |
| maxLength | int | 最大长度 | 100 |
| maxLengthEnforced | bool | 是否强制最大长度 | true |
| onChanged | ValueChanged | 文本改变回调 | (text) {} |
| onSubmitted | ValueChanged | 提交回调 | (text) {} |
| onEditingComplete | VoidCallback | 编辑完成回调 | () {} |
| inputFormatters | List | 输入格式化器 | [...] |
| enabled | bool | 是否启用 | true |
| cursorWidth | double | 光标宽度 | 2.0 |
| cursorHeight | double | 光标高度 | null |
| cursorRadius | Radius | 光标圆角 | Radius.circular(2) |
| cursorColor | Color | 光标颜色 | Colors.blue |
| keyboardAppearance | Brightness | 键盘外观 | Brightness.light |
| scrollPadding | EdgeInsets | 滚动内边距 | EdgeInsets.all(20) |
| enableInteractiveSelection | bool | 是否启用交互选择 | true |
| textCapitalization | TextCapitalization | 文本大写 | TextCapitalization.none |
| autocorrect | bool | 是否自动更正 | true |
| smartDashesType | SmartDashesType | 智能破折号类型 | SmartDashesType.enabled |
| smartQuotesType | SmartQuotesType | 智能引号类型 | SmartQuotesType.enabled |
| enableSuggestions | bool | 是否启用建议 | true |
使用示例:
dart
TextField(
controller: _controller,
decoration: InputDecoration(
labelText: '用户名',
hintText: '请输入用户名',
prefixIcon: Icon(Icons.person),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
),
keyboardType: TextInputType.text,
textInputAction: TextInputAction.next,
onChanged: (value) {
print('输入: $value');
},
)
TextFormField Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| controller | TextEditingController | 文本控制器 | TextEditingController() |
| focusNode | FocusNode | 焦点节点 | FocusNode() |
| decoration | InputDecoration | 装饰 | InputDecoration(...) |
| keyboardType | TextInputType | 键盘类型 | TextInputType.text |
| textInputAction | TextInputAction | 键盘动作 | TextInputAction.done |
| style | TextStyle | 文本样式 | TextStyle(fontSize: 16) |
| textAlign | TextAlign | 文本对齐 | TextAlign.start |
| autofocus | bool | 是否自动聚焦 | false |
| obscureText | bool | 是否隐藏文本 | false |
| maxLines | int | 最大行数 | 1 |
| minLines | int | 最小行数 | null |
| maxLength | int | 最大长度 | 100 |
| maxLengthEnforced | bool | 是否强制最大长度 | true |
| onChanged | ValueChanged | 文本改变回调 | (text) {} |
| onSaved | FormFieldSetter | 保存回调 | (value) {} |
| validator | FormFieldValidator | 验证回调 | (value) {} |
| onFieldSubmitted | ValueChanged | 字段提交回调 | (value) {} |
| inputFormatters | List | 输入格式化器 | [...] |
| enabled | bool | 是否启用 | true |
| cursorWidth | double | 光标宽度 | 2.0 |
| cursorHeight | double | 光标高度 | null |
| cursorRadius | Radius | 光标圆角 | Radius.circular(2) |
| cursorColor | Color | 光标颜色 | Colors.blue |
| keyboardAppearance | Brightness | 键盘外观 | Brightness.light |
| scrollPadding | EdgeInsets | 滚动内边距 | EdgeInsets.all(20) |
| enableInteractiveSelection | bool | 是否启用交互选择 | true |
| textCapitalization | TextCapitalization | 文本大写 | TextCapitalization.none |
| autocorrect | bool | 是否自动更正 | true |
| smartDashesType | SmartDashesType | 智能破折号类型 | SmartDashesType.enabled |
| smartQuotesType | SmartQuotesType | 智能引号类型 | SmartQuotesType.enabled |
| enableSuggestions | bool | 是否启用建议 | true |
| autovalidateMode | AutovalidateMode | 自动验证模式 | AutovalidateMode.onUserInteraction |
| restorationId | String | 恢复ID | 'text_form_field' |
| initialValue | String | 初始值 | '' |
使用示例:
dart
TextFormField(
controller: _emailController,
decoration: InputDecoration(
labelText: '邮箱',
hintText: '请输入邮箱',
prefixIcon: Icon(Icons.email),
border: OutlineInputBorder(),
),
keyboardType: TextInputType.emailAddress,
validator: (value) {
if (value == null || value.isEmpty) {
return '请输入邮箱';
}
if (!value.contains('@')) {
return '请输入有效的邮箱地址';
}
return null;
},
onSaved: (value) {
_email = value;
},
)
Checkbox Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| value | bool | 是否选中 | true |
| onChanged | ValueChanged | 改变回调 | (value) {} |
| tristate | bool | 是否三态 | false |
| activeColor | Color | 选中颜色 | Colors.blue |
| checkColor | Color | 勾选标记颜色 | Colors.white |
| materialTapTargetSize | MaterialTapTargetSize | 点击目标大小 | MaterialTapTargetSize.padded |
| visualDensity | VisualDensity | 视觉密度 | VisualDensity.adaptivePlatformDensity |
| focusColor | Color | 焦点颜色 | Colors.blue.withOpacity(0.1) |
| hoverColor | Color | 悬停颜色 | Colors.blue.withOpacity(0.1) |
| overlayColor | MaterialStateProperty | 覆盖颜色 | MaterialStateProperty.all(Colors.blue.withOpacity(0.1)) |
| splashRadius | double | 水波纹半径 | 20.0 |
| focusNode | FocusNode | 焦点节点 | FocusNode() |
| autofocus | bool | 是否自动聚焦 | false |
| shape | OutlinedBorder | 形状 | RoundedRectangleBorder(...) |
| side | MaterialStateBorderSide | 边框 | MaterialStateBorderSide.resolveWith(...) |
使用示例:
dart
Checkbox(
value: _isChecked,
onChanged: (value) {
setState(() {
_isChecked = value ?? false;
});
},
activeColor: Colors.blue,
)
CheckboxListTile Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| value | bool | 是否选中 | true |
| onChanged | ValueChanged | 改变回调 | (value) {} |
| title | Widget | 标题 | Text('选项') |
| subtitle | Widget | 副标题 | Text('描述') |
| isThreeLine | bool | 是否三行 | false |
| dense | bool | 是否紧凑 | false |
| secondary | Widget | 次要Widget | Icon(Icons.info) |
| selected | bool | 是否选中 | false |
| controlAffinity | ListTileControlAffinity | 控件位置 | ListTileControlAffinity.platform |
| autofocus | bool | 是否自动聚焦 | false |
| contentPadding | EdgeInsetsGeometry | 内容内边距 | EdgeInsets.symmetric(horizontal: 16) |
| shape | ShapeBorder | 形状 | RoundedRectangleBorder(...) |
| tileColor | MaterialStateProperty | 瓦片颜色 | MaterialStateProperty.all(Colors.white) |
| selectedTileColor | MaterialStateProperty | 选中瓦片颜色 | MaterialStateProperty.all(Colors.blue.withOpacity(0.1)) |
| visualDensity | VisualDensity | 视觉密度 | VisualDensity.adaptivePlatformDensity |
| focusNode | FocusNode | 焦点节点 | FocusNode() |
| onFocusChange | ValueChanged | 焦点改变回调 | (value) {} |
| enableFeedback | bool | 是否启用反馈 | true |
使用示例:
dart
CheckboxListTile(
title: Text('记住密码'),
subtitle: Text下次登录时自动填充密码,
value: _rememberPassword,
onChanged: (value) {
setState(() {
_rememberPassword = value ?? false;
});
},
secondary: Icon(Icons.lock),
)
Radio Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| value | T | 当前值 | 1 |
| groupValue | T | 组值 | _selectedValue |
| onChanged | ValueChanged | 改变回调 | (value) {} |
| activeColor | Color | 选中颜色 | Colors.blue |
| fillColor | MaterialStateProperty | 填充颜色 | MaterialStateProperty.all(Colors.blue) |
| materialTapTargetSize | MaterialTapTargetSize | 点击目标大小 | MaterialTapTargetSize.padded |
| visualDensity | VisualDensity | 视觉密度 | VisualDensity.adaptivePlatformDensity |
| focusColor | Color | 焦点颜色 | Colors.blue.withOpacity(0.1) |
| hoverColor | Color | 悬停颜色 | Colors.blue.withOpacity(0.1) |
| overlayColor | MaterialStateProperty | 覆盖颜色 | MaterialStateProperty.all(Colors.blue.withOpacity(0.1)) |
| splashRadius | double | 水波纹半径 | 20.0 |
| focusNode | FocusNode | 焦点节点 | FocusNode() |
| autofocus | bool | 是否自动聚焦 | false |
| toggleable | bool | 是否可切换 | false |
使用示例:
dart
Radio<int>(
value: 1,
groupValue: _selectedValue,
onChanged: (value) {
setState(() {
_selectedValue = value;
});
},
activeColor: Colors.blue,
)
RadioListTile Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| value | T | 当前值 | 1 |
| groupValue | T | 组值 | _selectedValue |
| onChanged | ValueChanged | 改变回调 | (value) {} |
| title | Widget | 标题 | Text('选项') |
| subtitle | Widget | 副标题 | Text('描述') |
| isThreeLine | bool | 是否三行 | false |
| dense | bool | 是否紧凑 | false |
| secondary | Widget | 次要Widget | Icon(Icons.info) |
| selected | bool | 是否选中 | false |
| controlAffinity | ListTileControlAffinity | 控件位置 | ListTileControlAffinity.platform |
| autofocus | bool | 是否自动聚焦 | false |
| contentPadding | EdgeInsetsGeometry | 内容内边距 | EdgeInsets.symmetric(horizontal: 16) |
| shape | ShapeBorder | 形状 | RoundedRectangleBorder(...) |
| tileColor | MaterialStateProperty | 瓦片颜色 | MaterialStateProperty.all(Colors.white) |
| selectedTileColor | MaterialStateProperty | 选中瓦片颜色 | MaterialStateProperty.all(Colors.blue.withOpacity(0.1)) |
| visualDensity | VisualDensity | 视觉密度 | VisualDensity.adaptivePlatformDensity |
| focusNode | FocusNode | 焦点节点 | FocusNode() |
| onFocusChange | ValueChanged | 焦点改变回调 | (value) {} |
| enableFeedback | bool | 是否启用反馈 | true |
使用示例:
dart
RadioListTile<int>(
title: Text('选项一'),
subtitle: Text('这是选项一的描述'),
value: 1,
groupValue: _selectedOption,
onChanged: (value) {
setState(() {
_selectedOption = value;
});
},
secondary: Icon(Icons.looks_one),
)
Switch Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| value | bool | 是否开启 | true |
| onChanged | ValueChanged | 改变回调 | (value) {} |
| activeColor | Color | 开启颜色 | Colors.blue |
| activeTrackColor | Color | 开启轨道颜色 | Colors.blue.withOpacity(0.5) |
| inactiveThumbColor | Color | 关闭拇指颜色 | Colors.grey |
| inactiveTrackColor | Color | 关闭轨道颜色 | Colors.grey.withOpacity(0.5) |
| activeThumbImage | ImageProvider | 开启拇指图片 | AssetImage(...) |
| inactiveThumbImage | ImageProvider | 关闭拇指图片 | AssetImage(...) |
| materialTapTargetSize | MaterialTapTargetSize | 点击目标大小 | MaterialTapTargetSize.padded |
| dragStartBehavior | DragStartBehavior | 拖动开始行为 | DragStartBehavior.start |
| focusColor | Color | 焦点颜色 | Colors.blue.withOpacity(0.1) |
| hoverColor | Color | 悬停颜色 | Colors.blue.withOpacity(0.1) |
| focusNode | FocusNode | 焦点节点 | FocusNode() |
| autofocus | bool | 是否自动聚焦 | false |
| overlayColor | MaterialStateProperty | 覆盖颜色 | MaterialStateProperty.all(Colors.blue.withOpacity(0.1)) |
| splashRadius | double | 水波纹半径 | 20.0 |
| thumbColor | MaterialStateProperty | 拇指颜色 | MaterialStateProperty.all(Colors.blue) |
| trackColor | MaterialStateProperty | 轨道颜色 | MaterialStateProperty.all(Colors.grey) |
使用示例:
dart
Switch(
value: _isSwitched,
onChanged: (value) {
setState(() {
_isSwitched = value;
});
},
activeColor: Colors.blue,
activeTrackColor: Colors.blue.withOpacity(0.5),
)
Slider Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| value | double | 当前值 | 0.5 |
| onChanged | ValueChanged | 改变回调 | (value) {} |
| onChangeStart | ValueChanged | 开始改变回调 | (value) {} |
| onChangeEnd | ValueChanged | 结束改变回调 | (value) {} |
| min | double | 最小值 | 0.0 |
| max | double | 最大值 | 1.0 |
| divisions | int | 分段数 | 10 |
| label | String | 标签 | '50%' |
| activeColor | Color | 激活颜色 | Colors.blue |
| inactiveColor | Color | 非激活颜色 | Colors.grey |
| semanticFormatterCallback | SemanticFormatterCallback | 语义格式化回调 | (value) => '$value%' |
| focusNode | FocusNode | 焦点节点 | FocusNode() |
| autofocus | bool | 是否自动聚焦 | false |
| mouseCursor | MouseCursor | 鼠标光标 | SystemMouseCursors.click |
使用示例:
dart
Slider(
value: _sliderValue,
min: 0,
max: 100,
divisions: 20,
label: '${_sliderValue.round()}',
activeColor: Colors.blue,
onChanged: (value) {
setState(() {
_sliderValue = value;
});
},
)
DropdownButton Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| items | List<DropdownMenuItem> | 选项列表 | [...] |
| value | T | 当前值 | _selectedItem |
| onChanged | ValueChanged | 改变回调 | (value) {} |
| hint | Widget | 提示 | Text('请选择') |
| disabledHint | Widget | 禁用提示 | Text('不可用') |
| elevation | int | 阴影高度 | 8 |
| style | TextStyle | 文本样式 | TextStyle(fontSize: 16) |
| icon | Widget | 图标 | Icon(Icons.arrow_drop_down) |
| iconDisabledColor | Color | 禁用图标颜色 | Colors.grey |
| iconEnabledColor | Color | 启用图标颜色 | Colors.blue |
| iconSize | double | 图标大小 | 24.0 |
| isDense | bool | 是否紧凑 | false |
| isExpanded | bool | 是否展开 | false |
| itemHeight | double | 选项高度 | 48.0 |
| focusColor | Color | 焦点颜色 | Colors.blue.withOpacity(0.1) |
| focusNode | FocusNode | 焦点节点 | FocusNode() |
| autofocus | bool | 是否自动聚焦 | false |
| dropdownColor | Color | 下拉颜色 | Colors.white |
| underline | Widget | 下划线 | Container(...) |
| menuMaxHeight | double | 菜单最大高度 | 300.0 |
| onTap | VoidCallback | 点击回调 | () {} |
使用示例:
dart
DropdownButton<String>(
value: _selectedItem,
hint: Text('请选择'),
items: <String>['选项一', '选项二', '选项三'].map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (String? newValue) {
setState(() {
_selectedItem = newValue;
});
},
)
对话框Widget详解
AlertDialog Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| title | Widget | 标题 | Text('提示') |
| content | Widget | 内容 | Text('确定要删除吗?') |
| contentPadding | EdgeInsetsGeometry | 内容内边距 | EdgeInsets.fromLTRB(24, 20, 24, 24) |
| actions | List | 操作按钮列表 | [TextButton(...)] |
| actionsPadding | EdgeInsetsGeometry | 操作按钮内边距 | EdgeInsets.zero |
| actionsAlignment | MainAxisAlignment | 操作按钮对齐 | MainAxisAlignment.end |
| actionsOverflowButtonSpacing | double | 操作按钮溢出间距 | 8.0 |
| buttonPadding | EdgeInsetsGeometry | 按钮内边距 | EdgeInsets.all(8) |
| backgroundColor | Color | 背景颜色 | Colors.white |
| elevation | double | 阴影高度 | 24.0 |
| semanticLabel | String | 语义标签 | "警告对话框" |
| insetPadding | EdgeInsets | 插入内边距 | EdgeInsets.symmetric(horizontal: 40, vertical: 24) |
| clipBehavior | Clip | 裁剪行为 | Clip.none |
| shape | ShapeBorder | 形状 | RoundedRectangleBorder(...) |
| scrollable | bool | 是否可滚动 | false |
| alignment | AlignmentGeometry | 对齐方式 | Alignment.center |
使用示例:
dart
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('确认删除'),
content: Text('确定要删除这个项目吗?此操作无法撤销。'),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text('取消'),
),
ElevatedButton(
onPressed: () {
// 执行删除操作
Navigator.of(context).pop();
},
style: ElevatedButton.styleFrom(primary: Colors.red),
child: Text('删除'),
),
],
);
},
)
SimpleDialog Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| title | Widget | 标题 | Text('选择') |
| titlePadding | EdgeInsetsGeometry | 标题内边距 | EdgeInsets.fromLTRB(24, 24, 24, 0) |
| children | List | 子Widget列表 | [SimpleDialogOption(...)] |
| contentPadding | EdgeInsetsGeometry | 内容内边距 | EdgeInsets.fromLTRB(0, 12, 0, 16) |
| backgroundColor | Color | 背景颜色 | Colors.white |
| elevation | double | 阴影高度 | 24.0 |
| semanticLabel | String | 语义标签 | "选择对话框" |
| insetPadding | EdgeInsets | 插入内边距 | EdgeInsets.symmetric(horizontal: 40, vertical: 24) |
| clipBehavior | Clip | 裁剪行为 | Clip.none |
| shape | ShapeBorder | 形状 | RoundedRectangleBorder(...) |
| alignment | AlignmentGeometry | 对齐方式 | Alignment.center |
使用示例:
dart
showDialog(
context: context,
builder: (BuildContext context) {
return SimpleDialog(
title: Text('选择操作'),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
children: [
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, '查看');
},
child: Text('查看详情'),
),
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, '编辑');
},
child: Text('编辑信息'),
),
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, '删除');
},
child: Text('删除项目', style: TextStyle(color: Colors.red)),
),
],
);
},
)
BottomSheet Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| builder | WidgetBuilder | 构建器 | (context) => Container(...) |
| backgroundColor | Color | 背景颜色 | Colors.white |
| elevation | double | 阴影高度 | 0.0 |
| shape | ShapeBorder | 形状 | RoundedRectangleBorder(...) |
| clipBehavior | Clip | 裁剪行为 | Clip.none |
| constraints | BoxConstraints | 约束 | BoxConstraints(...) |
| onClosing | VoidCallback | 关闭回调 | () {} |
| enableDrag | bool | 是否启用拖动 | true |
| animationController | AnimationController | 动画控制器 | AnimationController(...) |
使用示例:
dart
showModalBottomSheet(
context: context,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
builder: (BuildContext context) {
return Container(
padding: EdgeInsets.all(20),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('底部菜单', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
SizedBox(height: 20),
ListTile(
leading: Icon(Icons.photo_library),
title: Text('相册'),
onTap: () {
Navigator.pop(context);
},
),
ListTile(
leading: Icon(Icons.camera_alt),
title: Text('拍照'),
onTap: () {
Navigator.pop(context);
},
),
],
),
);
},
)
DatePicker Widget
Flutter提供了两种日期选择器:
showDatePicker- Material Design风格showCupertinoModalPopup- iOS风格
showDatePicker 参数:
| 参数 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| context | BuildContext | 上下文 | context |
| initialDate | DateTime | 初始日期 | DateTime.now() |
| firstDate | DateTime | 最小日期 | DateTime(2020) |
| lastDate | DateTime | 最大日期 | DateTime(2025) |
| currentDate | DateTime | 当前日期 | DateTime.now() |
| selectableDayPredicate | SelectableDayPredicate | 可选日期判断 | (day) => day.isBefore(DateTime.now()) |
| initialEntryMode | DatePickerEntryMode | 初始进入模式 | DatePickerEntryMode.calendar |
| helpText | String | 帮助文本 | '选择日期' |
| cancelText | String | 取消文本 | '取消' |
| confirmText | String | 确认文本 | '确定' |
| errorFormatText | String | 错误格式文本 | '无效格式' |
| errorInvalidText | String | 错误无效文本 | '超出范围' |
| fieldLabelText | String | 字段标签文本 | '日期' |
| fieldHintText | String | 字段提示文本 | '月/日/年' |
| keyboardType | TextInputType | 键盘类型 | TextInputType.datetime |
| locale | Locale | 区域设置 | Locale('zh', 'CN') |
| textDirection | TextDirection | 文本方向 | TextDirection.ltr |
| builder | TransitionBuilder | 构建器 | (context, child) => child |
使用示例:
dart
Future<void> _selectDate(BuildContext context) async {
final DateTime? picked = await showDatePicker(
context: context,
initialDate: _selectedDate,
firstDate: DateTime(2020),
lastDate: DateTime(2025),
helpText: '选择生日',
cancelText: '取消',
confirmText: '确定',
locale: Locale('zh', 'CN'),
);
if (picked != null && picked != _selectedDate) {
setState(() {
_selectedDate = picked;
});
}
}
TimePicker Widget
showTimePicker 参数:
| 参数 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| context | BuildContext | 上下文 | context |
| initialTime | TimeOfDay | 初始时间 | TimeOfDay.now() |
| builder | TransitionBuilder | 构建器 | (context, child) => child |
| useRootNavigator | bool | 是否使用根导航器 | true |
| initialEntryMode | TimePickerEntryMode | 初始进入模式 | TimePickerEntryMode.dial |
| confirmText | String | 确认文本 | '确定' |
| cancelText | String | 取消文本 | '取消' |
| helpText | String | 帮助文本 | '选择时间' |
使用示例:
dart
Future<void> _selectTime(BuildContext context) async {
final TimeOfDay? picked = await showTimePicker(
context: context,
initialTime: _selectedTime,
helpText: '选择时间',
confirmText: '确定',
cancelText: '取消',
);
if (picked != null && picked != _selectedTime) {
setState(() {
_selectedTime = picked;
});
}
}
动画Widget详解
AnimatedContainer Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| alignment | AlignmentGeometry | 对齐方式 | Alignment.center |
| padding | EdgeInsetsGeometry | 内边距 | EdgeInsets.all(10) |
| color | Color | 背景色 | Colors.blue |
| decoration | BoxDecoration | 装饰 | BoxDecoration(...) |
| foregroundDecoration | BoxDecoration | 前景装饰 | BoxDecoration(...) |
| width | double | 宽度 | 200.0 |
| height | double | 高度 | 100.0 |
| constraints | BoxConstraints | 尺寸约束 | BoxConstraints(...) |
| margin | EdgeInsetsGeometry | 外边距 | EdgeInsets.all(10) |
| transform | Matrix4 | 变换矩阵 | Matrix4.rotationZ(0.1) |
| curve | Curve | 动画曲线 | Curves.easeInOut |
| duration | Duration | 动画时长 | Duration(milliseconds: 300) |
| child | Widget | 子Widget | Text('内容') |
使用示例:
dart
AnimatedContainer(
duration: Duration(milliseconds: 300),
curve: Curves.easeInOut,
width: _isExpanded ? 200 : 100,
height: _isExpanded ? 200 : 100,
decoration: BoxDecoration(
color: _isExpanded ? Colors.blue : Colors.red,
borderRadius: BorderRadius.circular(_isExpanded ? 20 : 10),
),
child: Center(child: Text('点击切换')),
)
AnimatedOpacity Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| opacity | double | 透明度 | 0.5 |
| curve | Curve | 动画曲线 | Curves.easeInOut |
| duration | Duration | 动画时长 | Duration(milliseconds: 300) |
| alwaysIncludeSemantics | bool | 是否始终包含语义 | false |
| child | Widget | 子Widget | Text('内容') |
使用示例:
dart
AnimatedOpacity(
opacity: _isVisible ? 1.0 : 0.0,
duration: Duration(milliseconds: 300),
curve: Curves.easeInOut,
child: Text('淡入淡出文本'),
)
Hero Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| tag | Object | 标识符 | 'hero-tag' |
| child | Widget | 子Widget | Image.asset(...) |
| createRectTween | CreateRectTween | 创建矩形补间 | (begin, end) => MaterialRectArcTween(begin: begin, end: end) |
| flightShuttleBuilder | FlightWidgetBuilder | 飞行穿梭构建器 | (context, animation, direction, fromContext, toContext) => ... |
| placeholderBuilder | PlaceholderBuilder | 占位符构建器 | (context, heroSize, child) => ... |
| transitionOnUserGestures | bool | 是否在用户手势上过渡 | false |
使用示例:
dart
// 在源页面
Hero(
tag: 'image-hero',
child: Image.asset('assets/image.jpg'),
)
// 在目标页面
Hero(
tag: 'image-hero',
child: Image.asset('assets/image.jpg'),
)
FadeTransition Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| opacity | Animation | 透明度动画 | _animation |
| alwaysIncludeSemantics | bool | 是否始终包含语义 | false |
| child | Widget | 子Widget | Text('内容') |
使用示例:
dart
class FadeTransitionExample extends StatefulWidget {
@override
_FadeTransitionExampleState createState() => _FadeTransitionExampleState();
}
class _FadeTransitionExampleState extends State<FadeTransitionExample>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(seconds: 2),
vsync: this,
)..repeat(reverse: true);
_animation = CurvedAnimation(
parent: _controller,
curve: Curves.easeIn,
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return FadeTransition(
opacity: _animation,
child: const Text('淡入淡出动画'),
);
}
}
ScaleTransition Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| scale | Animation | 缩放动画 | _animation |
| alignment | AlignmentGeometry | 对齐方式 | Alignment.center |
| child | Widget | 子Widget | Text('内容') |
使用示例:
dart
ScaleTransition(
scale: _animation,
alignment: Alignment.center,
child: Container(
width: 100,
height: 100,
color: Colors.blue,
),
)
RotationTransition Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| turns | Animation | 旋转动画 | _animation |
| alignment | AlignmentGeometry | 对齐方式 | Alignment.center |
| child | Widget | 子Widget | Text('内容') |
使用示例:
dart
RotationTransition(
turns: _animation,
alignment: Alignment.center,
child: Icon(Icons.refresh),
)
SlideTransition Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| position | Animation | 位置动画 | _animation |
| child | Widget | 子Widget | Text('内容') |
| textDirection | TextDirection | 文本方向 | TextDirection.ltr |
使用示例:
dart
SlideTransition(
position: _animation,
child: Container(
width: 100,
height: 100,
color: Colors.blue,
),
)
AnimatedBuilder Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| animation | Listenable | 动画 | _controller |
| builder | TransitionBuilder | 构建器 | (context, child) => ... |
| child | Widget | 子Widget | Text('内容') |
使用示例:
dart
AnimatedBuilder(
animation: _controller,
builder: (context, child) {
return Transform.rotate(
angle: _controller.value * 2 * math.pi,
child: child,
);
},
child: FlutterLogo(size: 100),
)
TweenAnimationBuilder Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| tween | Tween | 补间动画 | Tween(begin: 0, end: 1) |
| duration | Duration | 动画时长 | Duration(seconds: 1) |
| curve | Curve | 动画曲线 | Curves.easeInOut |
| builder | Widget Function(BuildContext context, T value, Widget? child) | 构建器 | (context, value, child) => ... |
| child | Widget | 子Widget | Text('内容') |
| onEnd | VoidCallback | 动画结束回调 | () {} |
使用示例:
dart
TweenAnimationBuilder<double>(
tween: Tween(begin: 0, end: 1),
duration: Duration(seconds: 1),
builder: (context, value, child) {
return Opacity(
opacity: value,
child: child,
);
},
child: Text('淡入动画'),
)
导航Widget详解
Navigator Widget
常用方法:
| 方法 | 参数 | 说明 |
|---|---|---|
| push | Route route | 推入新路由 |
| pop | [T? result] | 弹出当前路由 |
| pushNamed | String routeName | 推入命名路由 |
| pushReplacementNamed | String routeName | 替换当前路由 |
| popUntil | RoutePredicate predicate | 弹出直到满足条件 |
| pushAndRemoveUntil | Route route, RoutePredicate predicate | 推入并移除其他路由 |
使用示例:
dart
// 推入新页面
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondPage()),
);
// 弹出当前页面
Navigator.pop(context);
// 推入命名路由
Navigator.pushNamed(context, '/second');
// 替换当前路由
Navigator.pushReplacementNamed(context, '/home');
// 弹出直到根路由
Navigator.popUntil(context, (route) => route.isFirst);
// 推入并清除所有路由
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => LoginPage()),
(route) => false,
);
MaterialPageRoute Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| builder | WidgetBuilder | 页面构建器 | (context) => SecondPage() |
| settings | RouteSettings | 路由设置 | RouteSettings(name: '/second') |
| maintainState | bool | 是否保持状态 | true |
| fullscreenDialog | bool | 是否全屏对话框 | false |
| allowSnapshotting | bool | 是否允许快照 | true |
使用示例:
dart
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SecondPage(),
settings: RouteSettings(name: '/second'),
fullscreenDialog: false,
),
)
TabBar Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| tabs | List | 标签列表 | [Tab(text: '首页'), Tab(text: '消息')] |
| controller | TabController | 标签控制器 | TabController(length: 2, vsync: this) |
| isScrollable | bool | 是否可滚动 | false |
| padding | EdgeInsetsGeometry | 内边距 | EdgeInsets.zero |
| indicatorColor | Color | 指示器颜色 | Colors.blue |
| automaticIndicatorColorAdjustment | bool | 是否自动调整指示器颜色 | true |
| indicatorWeight | double | 指示器粗细 | 2.0 |
| indicatorPadding | EdgeInsetsGeometry | 指示器内边距 | EdgeInsets.zero |
| indicator | Decoration | 指示器装饰 | BoxDecoration(...) |
| indicatorSize | TabBarIndicatorSize | 指示器大小 | TabBarIndicatorSize.tab |
| labelColor | Color | 选中标签颜色 | Colors.blue |
| labelStyle | TextStyle | 选中标签样式 | TextStyle(fontSize: 16, fontWeight: FontWeight.bold) |
| labelPadding | EdgeInsetsGeometry | 选中标签内边距 | EdgeInsets.symmetric(horizontal: 16) |
| unselectedLabelColor | Color | 未选中标签颜色 | Colors.grey |
| unselectedLabelStyle | TextStyle | 未选中标签样式 | TextStyle(fontSize: 14) |
| dragStartBehavior | DragStartBehavior | 拖动开始行为 | DragStartBehavior.start |
| overlayColor | MaterialStateProperty | 覆盖颜色 | MaterialStateProperty.all(Colors.transparent) |
| splashFactory | InteractiveInkFeatureFactory | 水波纹工厂 | InkRipple.splashFactory |
| mouseCursor | MouseCursor | 鼠标光标 | SystemMouseCursors.click |
| enableFeedback | bool | 是否启用反馈 | true |
| onTap | ValueChanged | 点击回调 | (index) {} |
| physics | ScrollPhysics | 滚动物理特性 | null |
使用示例:
dart
TabBar(
controller: _tabController,
tabs: [
Tab(text: '首页'),
Tab(text: '消息'),
Tab(text: '我的'),
],
indicatorColor: Colors.blue,
labelColor: Colors.blue,
unselectedLabelColor: Colors.grey,
indicatorSize: TabBarIndicatorSize.label,
)
TabBarView Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| children | List | 子Widget列表 | [Page1(), Page2()] |
| controller | TabController | 标签控制器 | TabController(length: 2, vsync: this) |
| physics | ScrollPhysics | 滚动物理特性 | null |
| dragStartBehavior | DragStartBehavior | 拖动开始行为 | DragStartBehavior.start |
使用示例:
dart
TabBarView(
controller: _tabController,
children: [
HomePage(),
MessagePage(),
ProfilePage(),
],
)
BottomNavigationBar Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| items | List | 导航项列表 | [...] |
| currentIndex | int | 当前索引 | 0 |
| onTap | ValueChanged | 点击回调 | (index) {} |
| elevation | double | 阴影高度 | 8.0 |
| type | BottomNavigationBarType | 导航栏类型 | BottomNavigationBarType.fixed |
| fixedColor | Color | 固定颜色 | Colors.blue |
| backgroundColor | Color | 背景颜色 | Colors.white |
| iconSize | double | 图标大小 | 24.0 |
| selectedItemColor | Color | 选中项颜色 | Colors.blue |
| unselectedItemColor | Color | 未选中项颜色 | Colors.grey |
| selectedFontSize | double | 选中字体大小 | 14.0 |
| unselectedFontSize | double | 未选中字体大小 | 12.0 |
| selectedLabelStyle | TextStyle | 选中标签样式 | TextStyle(fontSize: 14) |
| unselectedLabelStyle | TextStyle | 未选中标签样式 | TextStyle(fontSize: 12) |
| showSelectedLabels | bool | 是否显示选中标签 | true |
| showUnselectedLabels | bool | 是否显示未选中标签 | true |
| mouseCursor | MouseCursor | 鼠标光标 | SystemMouseCursors.click |
| enableFeedback | bool | 是否启用反馈 | true |
| landscapeLayout | BottomNavigationBarLandscapeLayout | 横屏布局 | BottomNavigationBarLandscapeLayout.spread |
使用示例:
dart
BottomNavigationBar(
currentIndex: _currentIndex,
onTap: (index) {
setState(() {
_currentIndex = index;
});
},
type: BottomNavigationBarType.fixed,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: '首页',
),
BottomNavigationBarItem(
icon: Icon(Icons.message),
label: '消息',
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
label: '我的',
),
],
)
Drawer Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| child | Widget | 子Widget | ListView(...) |
| elevation | double | 阴影高度 | 16.0 |
| semanticLabel | String | 语义标签 | "侧边栏" |
| width | double | 宽度 | 304.0 |
| backgroundColor | Color | 背景颜色 | Colors.white |
| clipBehavior | Clip | 裁剪行为 | Clip.none |
| shape | ShapeBorder | 形状 | RoundedRectangleBorder(...) |
| alignment | AlignmentGeometry | 对齐方式 | null |
使用示例:
dart
Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: [
DrawerHeader(
decoration: BoxDecoration(
color: Colors.blue,
),
child: Text(
'用户信息',
style: TextStyle(
color: Colors.white,
fontSize: 24,
),
),
),
ListTile(
leading: Icon(Icons.home),
title: Text('首页'),
onTap: () {
Navigator.pop(context);
},
),
ListTile(
leading: Icon(Icons.settings),
title: Text('设置'),
onTap: () {
Navigator.pop(context);
},
),
],
),
)
AppBar Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| leading | Widget | 前置Widget | Icon(Icons.menu) |
| automaticallyImplyLeading | bool | 是否自动显示返回按钮 | true |
| title | Widget | 标题 | Text('标题') |
| actions | List | 操作按钮列表 | [Icon(Icons.search)] |
| flexibleSpace | Widget | 灵活空间 | Container(...) |
| bottom | PreferredSizeWidget | 底部Widget | TabBar(...) |
| elevation | double | 阴影高度 | 4.0 |
| shadowColor | Color | 阴影颜色 | Colors.black |
| shape | ShapeBorder | 形状 | RoundedRectangleBorder(...) |
| backgroundColor | Color | 背景颜色 | Colors.blue |
| foregroundColor | Color | 前景色 | Colors.white |
| iconTheme | IconThemeData | 图标主题 | IconThemeData(color: Colors.white) |
| actionsIconTheme | IconThemeData | 操作图标主题 | IconThemeData(color: Colors.white) |
| textTheme | TextTheme | 文本主题 | TextTheme(...) |
| primary | bool | 是否为主应用栏 | true |
| centerTitle | bool | 标题是否居中 | false |
| titleSpacing | double | 标题间距 | NavigationToolbar.kMiddleSpacing |
| toolbarOpacity | double | 工具栏透明度 | 1.0 |
| bottomOpacity | double | 底部透明度 | 1.0 |
| toolbarHeight | double | 工具栏高度 | kToolbarHeight |
| leadingWidth | double | 前置Widget宽度 | 56.0 |
| backwardsCompatibility | bool | 是否向后兼容 | false |
| toolbarTextStyle | TextStyle | 工具栏文本样式 | TextStyle(...) |
| titleTextStyle | TextStyle | 标题文本样式 | TextStyle(...) |
| systemOverlayStyle | SystemUiOverlayStyle | 系统覆盖层样式 | SystemUiOverlayStyle(...) |
使用示例:
dart
AppBar(
title: Text('首页'),
centerTitle: true,
backgroundColor: Colors.blue,
elevation: 0,
leading: IconButton(
icon: Icon(Icons.menu),
onPressed: () {
Scaffold.of(context).openDrawer();
},
),
actions: [
IconButton(
icon: Icon(Icons.search),
onPressed: () {},
),
IconButton(
icon: Icon(Icons.more_vert),
onPressed: () {},
),
],
bottom: TabBar(
controller: _tabController,
tabs: [
Tab(text: '推荐'),
Tab(text: '热门'),
],
),
)
状态管理Widget详解
StatefulWidget Widget
| 方法 | 说明 |
|---|---|
| createState | 创建状态对象 |
| initState | 初始化状态 |
| didChangeDependencies | 依赖改变时调用 |
| build | 构建UI |
| didUpdateWidget | Widget更新时调用 |
| setState | 更新状态 |
| deactivate | 停用状态 |
| dispose | 销毁状态 |
| reassemble | 热重载时调用 |
使用示例:
dart
class CounterWidget extends StatefulWidget {
@override
_CounterWidgetState createState() => _CounterWidgetState();
}
class _CounterWidgetState extends State<CounterWidget> {
int _counter = 0;
void _increment() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Column(
children: [
Text('计数: $_counter'),
ElevatedButton(
onPressed: _increment,
child: Text('增加'),
),
],
);
}
}
InheritedWidget Widget
| 方法 | 说明 |
|---|---|
| of | 获取最近的InheritedWidget |
| updateShouldNotify | 是否通知依赖者更新 |
使用示例:
dart
class CounterData extends InheritedWidget {
final int count;
final VoidCallback onIncrement;
const CounterData({
Key? key,
required this.count,
required this.onIncrement,
required Widget child,
}) : super(key: key, child: child);
static CounterData of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<CounterData>()!;
}
@override
bool updateShouldNotify(CounterData oldWidget) {
return oldWidget.count != count;
}
}
// 使用
class CounterWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
final counterData = CounterData.of(context);
return Column(
children: [
Text('计数: ${counterData.count}'),
ElevatedButton(
onPressed: counterData.onIncrement,
child: Text('增加'),
),
],
);
}
}
Provider Widget
| Widget | 说明 |
|---|---|
| Provider | 基础Provider |
| ChangeNotifierProvider | 状态改变通知Provider |
| ListenableProvider | 可监听Provider |
| ValueListenableProvider | 值可监听Provider |
| StreamProvider | 流数据Provider |
| FutureProvider | Future数据Provider |
| Consumer | 消费Provider |
| Selector | 选择性消费Provider |
| Context.select | 选择性监听 |
| Context.watch | 监听Provider |
| Context.read | 读取Provider |
使用示例:
dart
// 定义模型
class Counter with ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
// 提供Provider
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => Counter(),
child: MyApp(),
),
);
}
// 消费Provider
class CounterWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
final counter = context.watch<Counter>();
return Column(
children: [
Text('计数: ${counter.count}'),
ElevatedButton(
onPressed: () => context.read<Counter>().increment(),
child: Text('增加'),
),
],
);
}
}
StreamBuilder Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| stream | Stream | 数据流 | _stream |
| initialData | T | 初始数据 | null |
| builder | AsyncWidgetBuilder | 构建器 | (context, snapshot) => ... |
使用示例:
dart
StreamBuilder<int>(
stream: _counterStream,
initialData: 0,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('错误: ${snapshot.error}');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
}
return Text('计数: ${snapshot.data}');
},
)
FutureBuilder Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| future | Future | Future对象 | _future |
| initialData | T | 初始数据 | null |
| builder | AsyncWidgetBuilder | 构建器 | (context, snapshot) => ... |
使用示例:
dart
FutureBuilder<String>(
future: _loadData(),
initialData: '加载中...',
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('错误: ${snapshot.error}');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
}
return Text('数据: ${snapshot.data}');
},
)
高级Widget详解
CustomPaint Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| painter | CustomPainter | 自定义绘制器 | _MyPainter() |
| foregroundPainter | CustomPainter | 前景绘制器 | _MyForegroundPainter() |
| size | Size | 尺寸 | Size(200, 200) |
| isComplex | bool | 是否复杂 | false |
| willChange | bool | 是否会改变 | false |
| child | Widget | 子Widget | Container(...) |
使用示例:
dart
class MyPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = Colors.blue
..style = PaintingStyle.fill;
canvas.drawCircle(Offset(size.width / 2, size.height / 2), 50, paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) => false;
}
// 使用
CustomPaint(
size: Size(200, 200),
painter: MyPainter(),
)
CustomScrollView + Slivers
| Sliver Widget | 说明 |
|---|---|
| SliverAppBar | 可折叠应用栏 |
| SliverList | 列表 |
| SliverGrid | 网格 |
| SliverPadding | 内边距 |
| SliverToBoxAdapter | 普通Widget适配器 |
| SliverFixedExtentList | 固定高度列表 |
| SliverFillRemaining | 填充剩余空间 |
使用示例:
dart
CustomScrollView(
slivers: [
SliverAppBar(
expandedHeight: 200,
floating: true,
pinned: true,
flexibleSpace: FlexibleSpaceBar(
title: Text('CustomScrollView'),
),
),
SliverPadding(
padding: EdgeInsets.all(10),
sliver: SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) => ListTile(title: Text('Item $index')),
childCount: 20,
),
),
),
],
)
NotificationListener Widget
| 属性 | 类型 | 说明 | 示例值 |
|---|---|---|---|
| onNotification | NotificationListenerCallback | 通知回调 | (notification) {} |
| child | Widget | 子Widget | ListView() |
使用示例:
dart
NotificationListener<ScrollNotification>(
onNotification: (scrollNotification) {
if (scrollNotification is ScrollStartNotification) {
print('开始滚动');
} else if (scrollNotification is ScrollEndNotification) {
print('结束滚动');
}
return false;
},
child: ListView.builder(
itemCount: 100,
itemBuilder: (context, index) => ListTile(title: Text('Item $index')),
),
)
性能优化Widget详解
const Widget
使用const构造函数可以避免Widget重建,提高性能。
使用示例:
dart
// 好的做法
const Text('静态文本')
const Icon(Icons.home)
// 避免的做法
Text('静态文本')
Icon(Icons.home)
ListView.builder
对于大量数据的列表,使用ListView.builder而不是ListView,可以按需创建Widget,提高性能。
使用示例:
dart
ListView.builder(
itemCount: 10000,
itemBuilder: (context, index) {
return ListTile(title: Text('Item $index'));
},
)
AutomaticKeepAliveClientMixin
保持页面状态,避免重建。
使用示例:
dart
class MyPage extends StatefulWidget {
@override
_MyPageState createState() => _MyPageState();
}
class _MyPageState extends State<MyPage> with AutomaticKeepAliveClientMixin {
@override
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
super.build(context);
return ListView.builder(
itemCount: 100,
itemBuilder: (context, index) => ListTile(title: Text('Item $index')),
);
}
}
RepaintBoundary
限制重绘范围,提高性能。
使用示例:
dart
RepaintBoundary(
child: ComplexWidget(),
)
LayoutBuilder
基于约束条件构建Widget,避免不必要的重建。
使用示例:
dart
LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth > 600) {
return DesktopLayout();
} else {
return MobileLayout();
}
},
)
总结
Flutter的Widget系统非常强大和灵活,掌握这些Widget的详细属性和使用方法,可以帮助开发者构建出高质量、高性能的Flutter应用。建议开发者:
- 熟练掌握各类Widget的常用属性和高级用法
- 理解Widget的渲染原理和性能优化技巧
- 合理选择状态管理方案
- 多实践,多查看官方文档和示例代码
- 关注Flutter新版本的新特性和改进
希望这份详细的Widget指南对你的Flutter开发有所帮助!