Flutter入门笔记系列文章部分内容来源于《Flutter 实战》,如有侵权请联系删除!
Material 组件库中提供了多种按钮组件如RaisedButton、FlatButton、OutlineButton等,它们都是直接或间接对RawMaterialButton组件的包装定制,所以他们大多数属性都和RawMaterialButton一样。在介绍各个按钮时我们先介绍其默认外观,而按钮的外观大都可以通过属性来自定义,我们在后面统一介绍这些属性。所有Material 库中的按钮都有如下相同点:
- 按下时都会有“水波动画”(又称“涟漪动画”,就是点击时按钮上会出现水波荡漾的动画)。
- 有一个onPressed属性来设置点击回调,当按钮按下时会执行该回调,如果不提供该回调则按钮会处于禁用状态,禁用状态不响应用户点击。
- RaisedButton 即"漂浮"按钮,它默认带有阴影和灰色背景。按下后,阴影会变大。
- FlatButton即扁平按钮,默认背景透明并不带阴影。按下后,会有背景色。
- OutlineButton默认有一个边框,不带阴影且背景透明。按下后,边框颜色会变亮、同时出现背景和阴影(较弱)。
- IconButton是一个可点击的Icon,不包括文字,默认没有背景,点击后会出现背景。
- RaisedButton、FlatButton、OutlineButton都有一个icon 构造函数,通过它可以轻松创建带图标的按钮。
RaisedButton(
child: Text("RaisedButton"),
onPressed: () {
},
),
FlatButton(
child: Text("FlatButton"),
onPressed: () {
},
),
OutlineButton(
child: Text("OutlineButton"),
onPressed: () {
},
),
IconButton(
icon: Icon(Icons.thumb_up),
onPressed: () {},
),
RaisedButton.icon(
icon: Icon(Icons.send),
label: Text("RaisedButton.icon"),
onPressed: () {
},
),
OutlineButton.icon(
icon: Icon(Icons.add),
label: Text("OutlineButton.icon"),
onPressed: () {
},
),
FlatButton.icon(
icon: Icon(Icons.info),
label: Text("FlatButton.icon"),
onPressed: () {
},
),
运行看看这些按钮长什么样吧!
Material按钮
上面的按钮定义都很简单,看起来也很普通。如果你是一个有追求的人,想写出更加炫酷的按钮,那么请继续学习按钮属性。由于它们的大部分属性都一样,所以下面的内容以FlatButton为例。
我们先通过源码看看都有什么属性:
const FlatButton({
...
@required this.onPressed, //按钮点击回调
this.textColor, //按钮文字颜色
this.disabledTextColor, //按钮禁用时的文字颜色
this.color, //按钮背景颜色
this.disabledColor,//按钮禁用时的背景颜色
this.highlightColor, //按钮按下时的背景颜色
this.splashColor, //点击时,水波动画中水波的颜色
this.colorBrightness,//按钮主题,默认是浅色主题
this.padding, //按钮的填充
this.shape, //外形
@required this.child, //按钮的内容
})
了解了这些属性的含义,我们来尝试着定义一个
FlatButton(
child: Text("FlatButton"),
textColor: Colors.white,
color: Colors.blue,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
splashColor: Colors.lightBlueAccent,
onPressed: () {},
)
按钮效果如下
蓝色圆角按钮
如果希望按钮带有阴影,把FlatButton换成RaisedButton即可。对比一下效果:
RaisedButton与FlatButton对比