Flutter 里有很多的 Button 組件很多,常見的按鈕組件有:RaisedButton、FlatButton、IconButton、OutlineButton、ButtonBar、FloatingActionButton 等。
- aisedButton :凸起的按鈕,其實就是 Material Design 風格的 Button
- FlatButton :扁平化的按鈕
- OutlineButton:線框按鈕
- IconButton :圖標按鈕
- ButtonBar:按鈕組
- FloatingActionButton:浮動按鈕
常用屬性
在flutter中,按鈕組件有以下常用屬性:
-
onPressed :必填參數,按下按鈕時觸發的回調,接收一個方法,傳 null 表示按鈕禁用,會顯示禁用相關樣式
- child :文本控件
- textColor :文本顏色
- color :文本顏色
- disabledColor :按鈕禁用時的顏色
- disabledTextColor :按鈕禁用時的文本顏色
-
splashColor :點擊按鈕時水波紋的顏色
-
highlightColor :點擊(長按)按鈕后按鈕的顏色
- elevation :陰影的范圍,值越大陰影范圍越大
-
padding :內邊距
-
shape :設置按鈕的形狀
基本使用
class HomeContent extends StatelessWidget{ @override Widget build(BuildContext context) { return Column( children: <Widget>[ Row( children: <Widget>[ RaisedButton( child:Text('普通按鈕'), onPressed: (){ print("這是一個普通按鈕"); }, ), ], ), ], ); } }
上面使用RaisedButton組件實現了一個最簡單的按鈕,然后,可以在此基礎上添加各種樣式:
設置按鈕寬高
在上面的常用屬性中,是沒有寬高屬性的,因此如果需要人為調整按鈕的大小,需要在按鈕的外層套一層Container,然后設置這個Container的寬高:
自適應按鈕
按鈕圖標
圓角按鈕和圓形按鈕
圖標按鈕
其他按鈕
按鈕組ButtonBar
自定義按鈕組件
如果需要多次使用按鈕,每次都像上面那樣寫的話,會十分麻煩,因此,可以在按鈕組件的基礎上進行簡單的封裝,實現自己的按鈕組件:
class MyButton extends StatelessWidget { final text; final pressed; final double width; final double height; const MyButton({this.text='',this.pressed=null,this.width=80,this.height=30}) ; @override Widget build(BuildContext context) { return Container( height: this.height, width: this.width, child: RaisedButton( child: Text(this.text), onPressed:this.pressed , ), ); } }
代碼下載:點這里(提取碼:axtj)