[英]How to change a specific Icon color in flutter?
I'm trying to change an IconButton's color when the user clicks on it, I've tried setting a state when user clicks on it, but the problem is that every Icon in the page changes color i want this to happen to the buttons that user clicks not all of them, these icons are for social media posts so i cant define a variable.我试图在用户单击它时更改 IconButton 的颜色,我尝试在用户单击它时设置 state,但问题是页面中的每个图标都会改变颜色我希望这发生在按钮上用户并非全部点击,这些图标用于社交媒体帖子,因此我无法定义变量。
Padding(
padding: EdgeInsets.fromLTRB(15.0, 15.0, 15.0, 10.0),
child : Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
IconButton(
icon: Icon(
Icons.favorite_border,
color: Colors.black,
size : 25.0
),
onPressed: () {
},
),
Text(
'29k',
style: TextStyle(
color : Colors.black,
fontSize: 15.0,
),
),
SizedBox(width: 10.0,),
IconButton(
icon: Icon(
Icons.question_answer,
color: _likeButtonColor,
size : 25.0
),
onPressed: () {
print(games[index]['posts']);
setState(() {
_likeButtonColor = Colors.red;
});
},
),
Text(
'1312',
style: TextStyle(
color : Colors.black,
fontSize: 15.0,
),
)
],
),
),
The problem is that you are using same variable for all IconButton widget's color property.问题是您对所有 IconButton 小部件的颜色属性使用相同的变量。
You have to create a list which hold the value of color for each items let me show you with example.您必须创建一个列表,其中包含每个项目的颜色值,让我通过示例向您展示。
class Delet2 extends StatefulWidget {
@override
_Delet2State createState() => _Delet2State();
}
class _Delet2State extends State<Delet2> with SingleTickerProviderStateMixin {
List<Color> _colors = [];
getdatafromserver() async {
await Future.delayed(
Duration(seconds: 2)); //this show you are fetching data from server
_colors =
List.generate(10, (index) => Colors.amber); // here 10 is items.length
setState(() {});
}
@override
void initState() {
super.initState();
getdatafromserver();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: _colors.length ?? 0,
itemBuilder: (_, index) {
return IconButton(
icon: Icon(Icons.question_answer,
color: _colors[index], size: 25.0),
onPressed: () {
setState(() {
_colors[index] = Colors.red;
});
});
},
),
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.