Flutter 中的按钮组件介绍
Material 组件库中提供了多种按钮组件如ElevatedButton、TextButton、OutlineButton等,它们都是直接或间接对RawMaterialButton组件的包装定制,所以他们大多数属性都和RawMaterialButton一样。在介绍各个按钮时我们先介绍其默认外观,而按钮的外观大都可以通过属性来自定义,我们在后面统一介绍这些属性。另外,所有 Material 库中的按钮都有如下相同点:
- 按下时都会有“水波动画”(又称“涟漪动画”,就是点击时按钮上会出现水波扩散的动画)。
- 有一个onPressed属性来设置点击回调,当按钮按下时会执行该回调,如果不提供该回调则按钮会处于禁用状态,禁用状态不响应用户点击。
按钮组件中的属性
属性名称 | 属性值 |
---|---|
onPressed | 必填参数,按下按钮时触发的回调,接收一个方法,传 null 表示按钮禁用,会显示禁用相关样式 |
child | 文本控件 |
textColor | 文本颜色 |
color | 按钮的颜色 |
disabledColor | 按钮禁用时的颜色 |
disabledTextColor | 按钮禁用时的文本颜色 |
splashColor | 点击按钮时水波纹的颜色 |
highlightColor | 点击(长按)按钮后按钮的颜色 |
elevation | 阴影的范围,值越大阴影范围越大 |
padding | 内边距 |
shape | 设置按钮的形状 |
shape: RoundedRectangleBorder(
borderRadius:BorderRadius.circular(10),
)
shape: CircleBorder(
side: BorderSide(
color: Colors.white,
)
Flutter中的按钮组件主要有一下几种
RaisedButton :凸起的按钮,其实就是 Material Design 风格的 Button(最新版本中被ElevatedButton代替)
FlatButton :扁平化的按钮(最新版本中被TextButton代替)
OutlineButton :线框按钮(最新版本中被OutlinedButton代替)
IconButton :图标按钮
ButtonBar:按钮组
FloatingActionButton:浮动按钮
ElevatedButton
ElevatedButton 即"漂浮"按钮,它默认带有阴影和灰色背景。按下后,阴影会变大,如图所示:
ElevatedButton(
child: Text("normal"),
onPressed: () {},
);
TextButton
TextButton即文本按钮,默认背景透明并不带阴影。按下后,会有背景色,如图所示:
TextButton(
child: Text("normal"),
onPressed: () {},
)
OutlinedButton
OutlinedButton默认有一个边框,不带阴影且背景透明。按下后,边框颜色会变亮、同时出现背景和阴影(较弱),如图所示:
OutlinedButton(
child: Text("normal"),
onPressed: () {},
)
IconButton
IconButton是一个可点击的Icon,不包括文字,默认没有背景,点击后会出现背景,如图所示:
IconButton(
icon: Icon(Icons.thumb_up),
onPressed: () {},
)
带图标的按钮
ElevatedButton、TextButton、OutlineButton都有一个icon 构造函数,通过它可以轻松创建带图标的按钮,如图所示
ElevatedButton.icon(
icon: Icon(Icons.send),
label: Text("发送"),
onPressed: _onPressed,
),
OutlineButton.icon(
icon: Icon(Icons.add),
label: Text("添加"),
onPressed: _onPressed,
),
TextButton.icon(
icon: Icon(Icons.info),
label: Text("详情"),
onPressed: _onPressed,
),
FloatingActionButton
浮动按钮,跟安卓里面的是一样的,可以配合Scaffold实现很多有意思的布局样式,还有就是FloatingActionButton如果存在多个需要指定heroTag
Center(
child: FloatingActionButton(
child: Text('FloatingActionButton'),
onPressed: () {
ToastUtil.showToast('FloatingActionButton');
}),
),
Center(
child: FloatingActionButton(
heroTag: '2',
child: Icon(Icons.add),
onPressed: () {
ToastUtil.showToast('FloatingActionButton');
}),
),
ButtonBar
这里额外介绍一个widget:ButtonBar,它里面可以放多个Button,ButtonBar可以多里面的button做统一样式处理
Container(
child: ButtonBar(
buttonPadding: EdgeInsets.all(10),
buttonHeight: 50,
alignment: MainAxisAlignment.start,
buttonTextTheme: ButtonTextTheme.primary,
layoutBehavior: ButtonBarLayoutBehavior.padded,
children: [
RaisedButton(
child: Text('button1'),
onPressed: () {
ToastUtil.showToast('button1');
},
),
RaisedButton(
child: Text('button2'),
onPressed: () {
ToastUtil.showToast('button2');
},
),
RaisedButton(
child: Text('button3'),
onPressed: () {
ToastUtil.showToast('button3');
},
),
],
),
),