在 Flutter 中,按钮的写法根据样式需求有多种选择,核心是通过不同的按钮组件(如 ElevatedButton
、TextButton
等)定义交互逻辑和外观,同时通过 child
属性指定按钮内部的显示内容(文字、图标等)。
一、Flutter 常用按钮的写法
Flutter 提供了多种预设样式的按钮组件,最常用的有以下几种,它们的核心结构相似(都需要 onPressed
回调和 child
内容):
1. ElevatedButton
(带阴影的悬浮按钮)
自带背景色和阴影,点击时有悬浮效果,适合重要操作(如 "提交""确认")。
dart
ElevatedButton(
// 点击回调(必传,null 时按钮会禁用)
onPressed: () {
print("ElevatedButton 被点击了");
},
// 按钮内部显示的内容(子组件,通常是 Text 或 Icon)
child: Text("确认"),
// 可选:自定义样式
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue, // 背景色
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10), // 内边距
textStyle: TextStyle(fontSize: 16), // 文字样式
),
)
2. TextButton
(文本按钮)
无背景色和阴影,只有文字,适合次要操作(如 "取消""跳过")。
dart
TextButton(
onPressed: () {
print("TextButton 被点击了");
},
child: Text("取消"),
style: TextButton.styleFrom(
foregroundColor: Colors.grey, // 文字颜色
),
)
3. OutlinedButton
(带边框的按钮)
有边框但无背景色,适合中等重要性操作(如 "编辑")。
dart
OutlinedButton(
onPressed: () {
print("OutlinedButton 被点击了");
},
child: Text("编辑"),
style: OutlinedButton.styleFrom(
side: BorderSide(color: Colors.green), // 边框样式
),
)
4. CupertinoButton
(iOS 风格按钮)
遵循 iOS 设计规范,样式更扁平,适合 Cupertino 风格的应用。
dart
CupertinoButton(
onPressed: () {
print("CupertinoButton 被点击了");
},
child: Text("iOS 按钮"),
color: CupertinoColors.activeBlue, // 背景色
)
5. 带图标的按钮(结合 Icon
组件)
按钮内部可以同时放图标和文字,通过 Row
组合成一个子组件:
dart
ElevatedButton(
onPressed: () {},
child: Row(
mainAxisSize: MainAxisSize.min, // 限制 Row 宽度为内容宽度
children: [
Icon(Icons.add, size: 18), // 图标
SizedBox(width: 8), // 图标和文字间距
Text("添加"), // 文字
],
),
)
总结
- Flutter 按钮通过
ElevatedButton
/TextButton
等组件实现,核心是onPressed
回调(处理点击)和child
属性(定义显示内容)。