我正在忙着创建一个博客应用,并陷入了类似的按钮功能。我想要做(如果用户在颤动列表视图中按下心脏按钮,它将变成红色,再次按下时它将进入原始状态),但是当我单击“喜欢”按钮时,列表显示。 这是我的代码段。
body: ListView.builder(
itemCount: 10,
physics: BouncingScrollPhysics(),
itemBuilder: (context, index) {
return Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(3.0, 3.0, 3.0, 0.0),
child: singleItem(index),
),
Divider(height: 0.5, color: Constants.greyColor),
],
);
},
),
Widget singleItem(int index) {
return ListTile(
leading: CircleAvatar(
radius: 25.0,
foregroundColor: Constants.orangeColor,
backgroundColor: Constants.orangeColor,
backgroundImage:
NetworkImage("https://png.pngtree.com/svg/20161113/ef1b24279e.png"),
),
trailing:
Text("Jul23", style: TextStyle(color: Constants.ligthGreyColor)),
title: Text("Jea @jeaBooty.jul23",
style: TextStyle(
color: Constants.slightBlackColor,
fontSize: 16.0,
fontWeight: FontWeight.w600)),
subtitle: Container(
margin: const EdgeInsets.symmetric(vertical: 8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Happy Birthday, hope you will have a wonderful Day"),
Container(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
IconButton(
onPressed: () {},
icon: Icon(Constants.commentIcon,
color: Constants.ligthGreyColor, size: 15.0),
),
SizedBox(width: 50.0),
IconButton(
onPressed: () {
if (!_isLike) {
setState(() {
_isLike = true;
color = Constants.orangeColor;
});
} else {
setState(() {
_isLike = false;
color = Constants.ligthGreyColor;
});
}
},
icon: Icon(Constants.crownIcon, color: color, size: 15.0),
),
],
),
),
],
),
),
);
}
答案 0 :(得分:0)
我想正如乔治·赫尔比特(George Herbet)在评论中提到的那样,似乎所有变量都使用了相同的变量_isLike
和color
。
也许您可以将isLike
的状态保存在List
中,即List<bool> _likes
,然后使用索引访问当前的状态,例如
...
IconButton(
onPressed: () {
setState(() {
_likes[index] = !_likes[index];
});
}
},
icon: Icon(Constants.crownIcon, color: _likes[index] ? Constants.orangeColor :
Constants.ligthGreyColor, size: 15.0),
),
...
答案 1 :(得分:0)
定义bool类型的List变量,如下所示:
List<bool> _likes = List.filled(length,true);
然后使用以下参数更改IconButton:
IconButton(
icon: _likes[index]
? Icon(Icons.favorite_border,
color: Colors.grey,)
: Icon(Icons.favorite,
color: Colors.red,) ,
onPressed: () {
setState(() {
_likes[index] = !_likes[index];
});
},)