[英]How to enable and disable button in GridView using Flutter?
我使用 flutter 在網格視圖中創建了按鈕。 現在我想在單擊按鈕時更改按鈕的顏色。 與 HTML 中的主動使用相同。 當我單擊按鈕時,按鈕應顯示在活動 state 中,當我單擊另一個按鈕時,第一個按鈕將被禁用,當前按鈕將被啟用。
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'My Mitsu',
style: TextStyle(color: Colors.black),
),
backgroundColor: Colors.white,
actions: <Widget>[
new RaisedButton(
child: new Text("Logout",
style: TextStyle(color: Colors.black, fontSize: 20.0)),
onPressed: () async {
log_out();
},
color: Colors.white,
)
],
),
backgroundColor: Colors.white,
body: Column(children: [
Expanded(
child: GridView.count(
crossAxisCount: countValue,
mainAxisSpacing: 35.0,
crossAxisSpacing: 35.0,
padding: const EdgeInsets.fromLTRB(20.0, 40.0, 40.0, 20.0),
childAspectRatio: (aspectWidth / aspectHeight),
children: <Widget>[
RaisedButton(
child: Text('Send Lift to Parking',
style: TextStyle(fontSize: 15.0)),
onPressed: () {
onPress(0);
showShortToast();
},
),
RaisedButton(
onPressed: () {
onPress(1);
showShortToast();
},
child: Text('Send Lift to 1st Floor',
style: TextStyle(fontSize: 15.0)),
),
RaisedButton(
onPressed: () {
onPress(2);
showShortToast();
},
child: Text('Send Lift to 2st Floor',
style: TextStyle(fontSize: 15.0)),
),
RaisedButton(
onPressed: () {
onPress(3);
showShortToast();
},
child: Text('Send Lift to 3st Floor',
style: TextStyle(fontSize: 15.0)),
),
RaisedButton(
onPressed: () {
onPress(4);
showShortToast();
},
child: Text('Send Lift to 4st Floor',
style: TextStyle(fontSize: 15.0)),
),
RaisedButton(
onPressed: () {
onPress(5);
showShortToast();
},
child: Text('Send Lift to 5st Floor',
style: TextStyle(fontSize: 15.0)),
),
RaisedButton(
onPressed: () {
onPress(6);
showShortToast();
},
child: Text('Send Lift to 6st Floor',
style: TextStyle(fontSize: 15.0)),
),
RaisedButton(
onPressed: () {
onPress(7);
showShortToast();
},
child: Text('Send Lift to 7st Floor',
style: TextStyle(fontSize: 15.0)),
),
],
),
),
]));
}
如果您沒有將 function 傳遞給按鈕的 onPressed 屬性,則該按鈕將自動禁用,(不傳遞 = 傳遞 null)
///button#1
FlatButton(
//change color according to state
color: button1Enabled? Colors.green:Colors.red;
onPressed: button1Enabled? (){ } : null;
)
///button#2
FlatButton(
onPressed: (){
setState(){
button1Enabled = !button1Enabled;
}
}
)
像這樣創建你的按鈕
RaisedButton(
onPressed: () {
onPressed(1);
},
color: currentIndex == 1 ? bottonColor : null,
child: Text('Send Lift to 1st Floor',
style: TextStyle(fontSize: 15.0)),
),
並像這樣創建 onPress 功能
onPressed(String floor) {
setState(() {
currentIndex = int.parse(floor);
bottonColor = Colors.red;
});
}
在 class currentIndex 和 buttonColor 之外創建兩個變量
int currentIndex = 0;
Color bottonColor;
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.