MaterialStateProperty<Color?>?和Color
- 當為TextButton等button添加顏色時,使用ButtonStyle為其添加顏色
TextButton(
onPressed: () {},
child: Text('text'),
style:
ButtonStyle(backgroundColor:Colors.white),
);
- 這樣設置會報錯,如題
MaterialStateProperty.all() 方法是設置點擊事件所有狀態下的樣式。
MaterialStateProperty.resolveWith() 可攔截分別設置不同狀態下的樣式。
- 如果所有的狀態時的顏色都相同,使用MaterialStateProperty.all(),如果不同狀態要使用不同的顏色時,用MaterialStateProperty.resolveWith(),例如:
TextButton(
onPressed: () {},
child: Text('text'),
style: ButtonStyle(
//backgroundColor:MaterialStateProperty.all(Colors.white)
backgroundColor: MaterialStateProperty.resolveWith(
(states) {
if (states.contains(MaterialState.focused) &&
!states.contains(MaterialState.pressed)) {
//獲取焦點時的顏色
return Colors.blue;
} else if (states.contains(MaterialState.pressed)) {
//按下時的顏色
return Colors.deepPurple;
}
//默認狀態使用灰色
return Colors.grey;
},
),
),
);