首页 > 解决方案 > 在 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)),
),

标签: flutter

解决方案


创建一个 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)),
      );
    }
  }

推荐阅读