body: Container(
child: FutureBuilder(
future: _getCandidates(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.data == null) {
return Container(
child: Center(
child: Text("Loading..."),
),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
final bool alreadySaved = _saved.contains(snapshot.data[index]);
return ListTile(
title: Text(snapshot.data[index].name,
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
)),
subtitle: Text(snapshot.data[index].province +
' | ' +
snapshot.data[index].district +
' | ' +
snapshot.data[index].party),
trailing: Icon(
alreadySaved
? Icons.favorite
: Icons.favorite_border,
color: alreadySaved ? Colors.red : null,
),
onTap: () {
setState(() {
if (alreadySaved) {
_saved.remove(snapshot.data[index]);
} else {
_saved.add(snapshot.data[index]);
}
});
},
);
});
}
}))
我试图重新创建“您的第一个Flutter应用程序,第2部分”,而不制作单独的_buildRow小部件并使用自定义json文件。上面的代码确实将点击后的心脏图标的状态设置为红色,但会立即取消操作,将心脏图标更改为默认设置。