Flutter 1.22版本新增了3個(gè)按鈕茄猫,TextButton狈蚤、OutlinedButton、ElevatedButton划纽,雖然以前的Button沒(méi)有被廢棄脆侮,但還是建議使用新的Button。
為什么會(huì)新增 Button勇劣?因?yàn)橄胍獙⒁郧暗陌粹o調(diào)整為統(tǒng)一的外觀比較麻煩靖避,因此以前經(jīng)常使用自定義的按鈕,而新增的按鈕解決了此類(lèi)問(wèn)題比默,可以非常方便的設(shè)置整體外觀幻捏。
1.22版本前的按鈕 | 主題 | 1.22版本后的按鈕 | 主題 |
---|---|---|---|
FlatButton | ButtonTheme | TextButton | TextButtonTheme |
OutlineButton | ButtonTheme | OutlinedButton | OutlinedButtonTheme |
RaisedButton | ButtonTheme | ElevatedButton | ElevatedButtonTheme |
樣式對(duì)比:
外觀上并沒(méi)有很大的不同,但TextButton命咐、OutlinedButton篡九、ElevatedButton 將外觀屬性集合為一個(gè) ButtonStyle,非常方便統(tǒng)一控制醋奠。
TextButton榛臼、OutlinedButton伊佃、ElevatedButton 這3個(gè)按鈕的用法和屬性完全相同,下面以 TextButton 為例讽坏。
簡(jiǎn)單使用:
TextButton(
child: Text('TextButton'),
)
當(dāng) onPressed 不設(shè)置或者設(shè)置為 null 時(shí)锭魔,按鈕為不可用狀態(tài)。
TextButton(
child: Text('TextButton'),
onPressed: (){},
)
onPressed 為點(diǎn)擊回調(diào)路呜,onLongPress 為長(zhǎng)按回調(diào)迷捧。
下面是最重要的屬性 ButtonStyle,一切外觀都是通過(guò)這個(gè)屬性進(jìn)行控制胀葱,屬性如下:
const ButtonStyle({
this.textStyle, //字體
this.backgroundColor, //背景色
this.foregroundColor, //前景色
this.overlayColor, // 高亮色漠秋,按鈕處于focused, hovered, or pressed時(shí)的顏色
this.shadowColor, // 陰影顏色
this.elevation, // 陰影值
this.padding, // padding
this.minimumSize, //最小尺寸
this.side, //邊框
this.shape, //形狀
this.mouseCursor, //鼠標(biāo)指針的光標(biāo)進(jìn)入或懸停在此按鈕的[InkWell]上時(shí)。
this.visualDensity, // 按鈕布局的緊湊程度
this.tapTargetSize, // 響應(yīng)觸摸的區(qū)域
this.animationDuration, //[shape]和[elevation]的動(dòng)畫(huà)更改的持續(xù)時(shí)間抵屿。
this.enableFeedback, // 檢測(cè)到的手勢(shì)是否應(yīng)提供聲音和/或觸覺(jué)反饋庆锦。例如,在Android上轧葛,點(diǎn)擊會(huì)產(chǎn)生咔噠聲搂抒,啟用反饋后,長(zhǎng)按會(huì)產(chǎn)生短暫的振動(dòng)尿扯。通常求晶,組件默認(rèn)值為true。
});
這些屬性的用法也和以前的不一樣衷笋,比如 textStyle 并不是直接設(shè)置 TextStyle芳杏,下面設(shè)置字體:
TextButton(
child: Text('TextButton'),
onPressed: () {},
style: ButtonStyle(
textStyle: MaterialStateProperty.all(TextStyle(fontSize: 20)),
),
)
注意:字體顏色的設(shè)置不通過(guò)textStyle 設(shè)置,而是通過(guò) foregroundColor:
TextButton(
child: Text('TextButton'),
onPressed: () {},
style: ButtonStyle(
foregroundColor: MaterialStateProperty.all(Colors.red),
),
)
根據(jù)按鈕的狀態(tài)改變字體顏色:
TextButton(
child: Text('TextButton'),
onPressed: () {},
style: ButtonStyle(
foregroundColor:
MaterialStateProperty.resolveWith((states) {
return states.contains(MaterialState.pressed)
? Colors.blue
: Colors.red;
}),
),
)
其他屬性用法和上面類(lèi)似辟宗,不在一一介紹爵赵。
進(jìn)行全局控制:
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 內(nèi)的屬性配置和單個(gè)按鈕的用法是一致的。
通過(guò)上面的介紹泊脐,建議使用 TextButton空幻、OutlinedButton、ElevatedButton 替換 FlatButton晨抡、OutlineButton氛悬、RaisedButton。
交流
老孟Flutter博客(330個(gè)控件用法+實(shí)戰(zhàn)入門(mén)系列文章):http://laomengit.com