Flutter 1.22版本新增了3個按鈕,TextButton、OutlinedButton、ElevatedButton,雖然之前的Button沒有被廢棄,但仍是建議使用新的Button。git
爲何會新增 Button?由於想要將之前的按鈕調整爲統一的外觀比較麻煩,所以之前常常使用自定義的按鈕,而新增的按鈕解決了此類問題,能夠很是方便的設置總體外觀。微信
1.22版本前的按鈕 | 主題 | 1.22版本後的按鈕 | 主題 |
---|---|---|---|
FlatButton | ButtonTheme | TextButton | TextButtonTheme |
OutlineButton | ButtonTheme | OutlinedButton | OutlinedButtonTheme |
RaisedButton | ButtonTheme | ElevatedButton | ElevatedButtonTheme |
樣式對比:ide
外觀上並無很大的不一樣,但TextButton、OutlinedButton、ElevatedButton 將外觀屬性集合爲一個 ButtonStyle,很是方便統一控制。佈局
TextButton、OutlinedButton、ElevatedButton 這3個按鈕的用法和屬性徹底相同,下面以 TextButton 爲例。字體
簡單使用:動畫
TextButton( child: Text('TextButton'), )
當 onPressed 不設置或者設置爲 null 時,按鈕爲不可用狀態。this
TextButton( child: Text('TextButton'), onPressed: (){}, )
onPressed 爲點擊回調,onLongPress 爲長按回調。3d
下面是最重要的屬性 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,下面設置字體:code
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】:
![]() |
![]() |