正如您在此处看到的代码,我有 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()),
答案 0 :(得分:1)
您可以在 index
类中添加一个 MyButtonModal
字段,作为每个按钮的唯一键。
初始化 index
中的 StatefulWidget
变量,每当您单击按钮时,将 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(),
),
),
);
}
}
如果您有任何疑问,请评论。