前言
Hi, 今天要教大家 Button 這個元件,教學內容只會擷取片段程式碼,建議大家搭配完整程式碼來練習。
完整程式碼
- IconButton:圖示按鈕
- TextButton:文字按鈕
- OutlineButton:邊框按鈕
- ElevatedButton:漂浮按鈕
可以加入小圖標的按鈕
color
:Icon的顏色
highlightColor
:當按鈕按下時的顏色
splashColor
:當按鈕按下時的水波顏色
icon
:按鈕Icon
onPressed
:按鈕按下時所調用的邏輯,若為null
則不使用
iconSize
: Icon大小,預設為24
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class DemoIconButton extends StatelessWidget { const DemoIconButton({Key? key}) : super(key: key);
@override Widget build(BuildContext context) { return Container( child: IconButton( iconSize: 50, color: Colors.amber, highlightColor: Colors.transparent, splashColor: Colors.transparent, icon: Icon(Icons.ac_unit), onPressed: () { log("click", name: "INFO"); }, ), ); } }
|
TextButton 元件,常用屬性
文字按鈕
style
:利用TextButton.styleFrom
變更按鈕顏色、風格
child
:子元件
onPressed
:點擊按鈕時觸發的邏輯
onLongPress
:長壓按鈕時觸發的邏輯
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class DemoTextButton extends StatelessWidget { const DemoTextButton({Key? key}) : super(key: key);
@override Widget build(BuildContext context) { return Container( child: TextButton( child: Text( "Hello", style: TextStyle(color: Colors.white), ), style: TextButton.styleFrom( backgroundColor: Colors.green, ), onPressed: () { log("click", name: "INFO"); }, onLongPress: () { log("long click", name: "INFO"); }, ), ); } }
|
會有編框的按鈕
style
:利用OutlinedButton.styleFrom
變更按鈕顏色、風格
child
:子元件
onPressed
:點擊按鈕時觸發的邏輯
onLongPress
:長壓按鈕時觸發的邏輯
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class DemoOutlinedButton extends StatelessWidget { const DemoOutlinedButton({Key? key}) : super(key: key);
@override Widget build(BuildContext context) { return Container( child: OutlinedButton( child: Text("Hello"), style: OutlinedButton.styleFrom( primary: Colors.white, backgroundColor: Colors.blueGrey, ), onPressed: () { log("click", name: "INFO"); }, onLongPress: () { log("long click", name: "INFO"); }, ), ); } }
|
這個按鈕會有漂浮的感覺。
style
:利用ElevatedButton.styleFrom
變更按鈕顏色、風格
child
:子元件
onPressed
:點擊按鈕時觸發的邏輯
onLongPress
:長壓按鈕時觸發的邏輯
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class DemoElevatedButton extends StatelessWidget { const DemoElevatedButton({Key? key}) : super(key: key);
@override Widget build(BuildContext context) { return Container( child: ElevatedButton( child: Text("Hello"), style: ElevatedButton.styleFrom( elevation: 20, ), onPressed: () { log("click", name: "INFO"); }, ), ); } }
|
鎖住按鈕
若將onPressed
後面帶null
的話,按鈕就會變成灰色不能按。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class DemoNullButton extends StatelessWidget { const DemoNullButton({Key? key}) : super(key: key);
@override Widget build(BuildContext context) { return Container( child: OutlinedButton( child: Text("Hello"), onPressed: null, ), ); } }
|