![](/img/trans.png)
[英]How to change the color of just ONE button when the button is clicked from a container with 9 buttons Flutter
[英]How to select JUST one button from 9 buttons? Flutter/Dart
正如您在這里看到的我的代碼,我有 9 個按鈕(從 1 到 9),如果我單擊其中一個,它們的顏色將變為藍色,但在我的代碼中,它有能力將它們全部變為藍色但我想要一些改變,其中只有一個改變。 例如,如果您單擊數字 2,數字 2 將為藍色,然后單擊數字 3,數字 3 將為藍色,數字 2 將為白色(默認)。 有什么幫助嗎?
class MyButtonModal {
final String buttonText;
bool changeButtonColor;
MyButtonModal({this.buttonText, this.changeButtonColor = false});
}
GridView.count(
shrinkWrap: true,
physics: ClampingScrollPhysics(),
mainAxisSpacing: 10,
crossAxisSpacing: 10,
childAspectRatio: 80 / 95,
crossAxisCount: 12,
children: _a.map((MyButtonModal f) {
return InkWell(
child: Container(
decoration: BoxDecoration(
color: f.changeButtonColor
? Colors.blue
: Colors.white,
borderRadius: BorderRadius.circular(5),
border: Border.all(color: Color(0xffaaaaaa))),
child: Center(
child: Text(f.buttonText),
)),
onTap: () {
setState(() {
f.changeButtonColor = !f.changeButtonColor;
});
},
);
}).toList()),
您可以在MyButtonModal
class 中添加一個index
字段,該字段將作為每個按鈕的唯一鍵。
初始化StatefulWidget
中的index
變量,並且每當您單擊按鈕時,將index
變量更新為按鈕的索引。
現在更改顏色檢查如果f.index == index
如果為真,則將顏色更改為藍色,否則為白色。
import 'package:flutter/material.dart';
class MyButtonModal {
final String buttonText;
// New field to uniquely identify a button
final int index;
MyButtonModal({this.buttonText, this.index});
}
class HomePage extends StatefulWidget {
HomePage({Key key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
// This will create nine [MyButtonModel] with index from 0 to 8
List<MyButtonModal> _a = List.generate(9,
(index) => MyButtonModal(buttonText: "Button ${index + 1}", index: index));
// Initialize index variable and set it to any value other than 0 to 8
int index = 999;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: GridView.count(
shrinkWrap: true,
physics: ClampingScrollPhysics(),
mainAxisSpacing: 10,
crossAxisSpacing: 10,
childAspectRatio: 80 / 95,
crossAxisCount: 12,
children: _a.map((MyButtonModal f) {
return InkWell(
child: Container(
decoration: BoxDecoration(
// Check if f.index == index
color: f.index == index ? Colors.blue : Colors.white,
borderRadius: BorderRadius.circular(5),
border: Border.all(color: Color(0xffaaaaaa))),
child: Center(
child: Text(f.buttonText),
)),
onTap: () {
// When button is tapped update index to the index of the button
setState(() {
index = f.index;
});
},
);
}).toList(),
),
),
);
}
}
如果您有任何疑問,請發表評論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.