Flutter 1.22版本新增了3个按钮,TextButton、OutlinedButton、ElevatedButton,尽管以前的Button没有被废除,但还是倡议应用新的Button。
为什么会新增 Button?因为想要将以前的按钮调整为对立的外观比拟麻烦,因而以前常常应用自定义的按钮,而新增的按钮解决了此类问题,能够十分不便的设置整体外观。
1.22版本前的按钮 | 主题 | 1.22版本后的按钮 | 主题 |
---|---|---|---|
FlatButton | ButtonTheme | TextButton | TextButtonTheme |
OutlineButton | ButtonTheme | OutlinedButton | OutlinedButtonTheme |
RaisedButton | ButtonTheme | ElevatedButton | ElevatedButtonTheme |
款式比照:
外观上并没有很大的不同,但TextButton、OutlinedButton、ElevatedButton 将外观属性汇合为一个 ButtonStyle,十分不便对立管制。
TextButton、OutlinedButton、ElevatedButton 这3个按钮的用法和属性完全相同,上面以 TextButton 为例。
简略应用:
TextButton( child: Text('TextButton'),)
当 onPressed 不设置或者设置为 null 时,按钮为不可用状态。
TextButton( child: Text('TextButton'), onPressed: (){},)
onPressed 为点击回调,onLongPress 为长按回调。
上面是最重要的属性 ButtonStyle,所有外观都是通过这个属性进行管制,属性如下:
const ButtonStyle({ this.textStyle, //字体 this.backgroundColor, //背景色 this.foregroundColor, //前景色 this.overlayColor, // 高亮色,按钮处于focused, hovered, or pressed时的色彩 this.shadowColor, // 暗影色彩 this.elevation, // 暗影值 this.padding, // padding this.minimumSize, //最小尺寸 this.side, //边框 this.shape, //形态 this.mouseCursor, //鼠标指针的光标进入或悬停在此按钮的[InkWell]上时。 this.visualDensity, // 按钮布局的紧凑水平 this.tapTargetSize, // 响应触摸的区域 this.animationDuration, //[shape]和[elevation]的动画更改的持续时间。 this.enableFeedback, // 检测到的手势是否应提供声音和/或触觉反馈。例如,在Android上,点击会产生咔哒声,启用反馈后,长按会产生短暂的振动。通常,组件默认值为true。});
这些属性的用法也和以前的不一样,比方 textStyle 并不是间接设置 TextStyle,上面设置字体:
TextButton( child: Text('TextButton'), onPressed: () {}, style: ButtonStyle( textStyle: MaterialStateProperty.all(TextStyle(fontSize: 20)), ),)
留神:字体色彩的设置不通过textStyle 设置,而是通过 foregroundColor:
TextButton( child: Text('TextButton'), onPressed: () {}, style: ButtonStyle( foregroundColor: MaterialStateProperty.all(Colors.red), ),)
依据按钮的状态扭转字体色彩:
TextButton( child: Text('TextButton'), onPressed: () {}, style: ButtonStyle( foregroundColor: MaterialStateProperty.resolveWith((states) { return states.contains(MaterialState.pressed) ? Colors.blue : Colors.red; }), ), )
其余属性用法和下面相似,不在一一介绍。
进行全局管制:
MaterialApp( title: 'Flutter Demo', theme: ThemeData( textButtonTheme: TextButtonThemeData( style: ButtonStyle() ), elevatedButtonTheme: ElevatedButtonThemeData( style: ButtonStyle() ), outlinedButtonTheme: OutlinedButtonThemeData( style: ButtonStyle() ) ), home: MyHomePage(title: 'Flutter Demo Home Page'),)
ButtonStyle 内的属性配置和单个按钮的用法是统一的。
通过下面的介绍,倡议应用 TextButton、OutlinedButton、ElevatedButton 替换 FlatButton、OutlineButton、RaisedButton。
交换
老孟Flutter博客(330个控件用法+实战入门系列文章):http://laomengit.com
欢送退出Flutter交换群(微信:laomengit)、关注公众号【老孟Flutter】: