flutter - 在 onTap ( Flutter ListItem ) 中执行函数后如何更改图标的颜色
问题描述
想要在点击时更改图标的颜色。默认情况下,如果项目已经收藏,则图标为红色,而其他图标为默认颜色。
如果用户点击图标使其收藏或取消收藏,我想在更新后更改颜色。
new ListTile(
trailing: InkWell(
child: Icon(Icons.share),
),
leading: InkWell(
onTap: () {
snapshot.data[index].isFavorite == 0
? makeFavorite(snapshot.data[index].id)
: makeUnfavorite(
snapshot.data[index].id);
},
child: snapshot.data[index].isFavorite == 1
? Icon(
Icons.favorite,
color: Colors.red,
)
: Icon(Icons.favorite)),
title: new Text(snapshot.data[index].body,
style: new TextStyle(
fontWeight: FontWeight.bold, fontSize: 14.0)),
),
解决方案
创建一个 Statefull 小部件以更改其状态
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Title'),
),
body: new ListView.builder(itemBuilder: (context, index) {
return new ListItem();
}),
);
}
class ListItem extends StatefulWidget {
@override
State<StatefulWidget> createState() => new _ItemView();
}
class _ItemView extends State<ListItem>{
bool isFavorite = false;
@override
Widget build(BuildContext context) {
return new ListTile(
trailing: InkWell(
child: Icon(Icons.share),
),
leading: InkWell(
onTap: () {
isFavorite = !isFavorite;
setState(() {
});
},
child: isFavorite ? Icon(
Icons.favorite,
color: Colors.red,
): Icon(Icons.favorite)),
title: new Text('Your Text',
style: new TextStyle(
fontWeight: FontWeight.bold, fontSize: 14.0)),
);
}
}
推荐阅读
- c++ - 将数据保存到二进制文件,哪种方法是正确的?
- python - Kivy 调试 Android:PermissionError[Errno 13]Permission denied: '/data/.notion-py'
- c++ - Visual Studio 2019 C++ 无法识别模板好友
- php - 通过 WSL2 使用 Docker 时的 PhpStorm 路径映射
- powershell - 使用 XPath 将 XML 转换为对象时出错
- node.js - 我如何从 RabbitMQ 消息发出 http 请求 - nodejs
- javascript - 如何将脚本添加到在每次页面加载时运行的 gatsby 页面?
- python - 如何在循环的迭代中停止以提高速度?Python3
- python - 将数据从一个函数传递给另一个函数
- java - 如何在 Spring Data Jpa 中对对象为 null 的元素进行排序