【发布时间】:2021-07-09 20:30:22
【问题描述】:
我是 Flutter 的新手,所以我试图构建一个可滚动的 listtile 对象。因此,在构建它之后,我尝试让图标按钮在按下时改变颜色,但当我按下一个按钮时,它会改变所有项目的颜色。我想这与为每个项目分配一个唯一的 id/key 有关,但不确定这是否是问题,甚至是如何做到这一点。代码如下:
class Lists extends StatefulWidget {
@override
_ListsState createState() => _ListsState();
}
class _ListsState extends State<Lists> {
Color _statusColor = Colors.grey;
List<ItemLists> items = [
ItemLists(
title: 'Best Music of the Year',
discription: 'Davido',
),
ItemLists(
title: 'Best Album Cover design',
discription: 'Brighter Press',
),
ItemLists(
title: 'Best Vocalist',
discription: 'Simi-Sola',
),
];
@override
Widget build(BuildContext context) {
return Column(
children: items.map(
(items) {
return Container(
child: Card(
child: ListTile(
leading: new IconButton(
icon: Icon(
Icons.star,
color: _statusColor,
),
tooltip: 'Add to Favorite',
onPressed: () {
setState(() {
if (_statusColor == Colors.grey) {
_statusColor = Colors.green;
} else {
_statusColor = Colors.grey;
}
});
}),
title: Text('${items.title}'),
subtitle: Text('${items.discription}'),
trailing: IconButton(icon: Icon(Icons.delete), onPressed: null),
)));
},
).toList());
}
}
提前致谢。
下面是修改后的代码
class Lists extends StatefulWidget {
@override
_ListsState createState() => _ListsState();
}
class _ListsState extends State<Lists> {
Color _statusColor = Colors.grey;
List<ItemLists> items = [
ItemLists(
title: 'Best Music of the Year',
discription: 'Davido',
favorite: false,
),
ItemLists(
title: 'Best Album Cover design',
discription: 'Brighter Press',
favorite: false,
),
ItemLists(
title: 'Best Vocalist',
discription: 'Simi-Sola',
favorite: false,
),
];
@override
Widget build(BuildContext context) {
return Column(
children: items.map(
(items) {
return Container(
child: Card(
child: ListTile(
leading: new IconButton(
icon: Icon(
Icons.star,
color: items.favorite ? Colors.green : Colors.grey,
),
tooltip: 'Add to Favorite',
onPressed: () {
setState(() {
items.favorite = !items.favorite;
});
}),
title: Text('${items.title}'),
subtitle: Text('${items.discription}'),
trailing: IconButton(icon: Icon(Icons.delete), onPressed: null),
)));
},
).toList());
}
}
那么下面是我的数据模型
class ItemLists {
String title;
String discription;
bool favorite;
ItemLists({this.title, this.discription, this.favorite});
}
我想做的是一个待办事项应用程序,用户可以在完成特定任务后轻松单击星形图标按钮。
【问题讨论】:
标签: flutter listview flutter-layout