我试图在用户单击时更改IconButton的颜色,我试图在用户单击时设置状态,但是问题是页面中的每个Icon都会更改颜色,我希望这种情况发生用户单击的按钮并非全部单击,这些图标用于社交媒体帖子,因此我无法定义变量。
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,
),
)
],
),
),
答案 0 :(得分:0)
问题是您对所有IconButton小部件的color属性使用了相同的变量。
您必须创建一个列表,其中包含每个项目的颜色值,让我为您展示示例。
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;
});
});
},
),
);
}
}