如何在onTap(Flutter ListItem)内执行函数后更改图标的颜色

Muh*_*han 5 flutter

想要改变点击时图标的颜色。默认情况下,如果项目已收藏,则图标为红色,而其他图标为默认颜色。

如果用户点击图标将其设为收藏或不收藏,我想在更新后更改颜色。

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)),
),
Run Code Online (Sandbox Code Playgroud)

Muh*_*han 2

这样解决了问题(更新代码)

列表图块代码

new ListTile(
                        trailing: InkWell(
                          child: Icon(Icons.share),
                        ),
                        leading: InkWell(
                            onTap: () {
                              snapshot.data[index].isFavorite == 0
                                  ? makeFavorite(
                                      snapshot.data[index].id, index)
                                  : makeUnfavorite(
                                      snapshot.data[index].id, index);
                            },
                            child: (indexes[index] == 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)),
                      ),
Run Code Online (Sandbox Code Playgroud)

改变状态的函数

 makeFavorite(int id, int index) {
    // operations to be performed
    // end of operations to be performed
    setState(() {
      indexes[index] = 1;
    });
  }
Run Code Online (Sandbox Code Playgroud)