【发布时间】:2021-04-25 13:22:49
【问题描述】:
我有一个 Flutter 网站,其中有一个包含歌曲的列表。用户可以将歌曲添加到列表中,我想实现在用户添加新歌曲后,如果歌曲已经存在,则会检查列表。如果它已经存在,则增加现有项目的 likes 属性。如果它不存在,则添加该项目。
我用 list.contains(item.title) 试过了,但它不能正常工作。
这是我的代码:
class _songlistState extends State<SonglistView> {
TextEditingController textfieldControllersong;
List<Song> list = List<Song>();
@override
void initState() {
textfieldControllersong = TextEditingController();
super.initState();
}
@override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
Expanded(child: SizedBox(height: 400.0, child: buildListView())),
Expanded(
child: Center(
child: TextField(
cursorColor: primaryColor,
decoration: new InputDecoration(
hintText: 'Enter your Song',
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: primaryColor)),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: primaryColor)),
),
controller: textfieldControllersong,
),
),
),
SizedBox(
width: 20,
),
FloatingActionButton(
child: const Icon(Icons.add),
backgroundColor: primaryColor,
onPressed: () {
print('hallo');
checkSong(Song(
title: textfieldControllersong.text, like: false, likes: 0));
/*addSong(Song(
title: textfieldControllersong.text, like: false, likes: 0));*/
},
)
],
);
}
Widget buildListView() {
return ListView.builder(
itemCount: list.length,
itemBuilder: (context, index) {
return buildItem(list[index]);
},
);
}
Widget buildItem(Song item) {
return Card(
child: ListTile(
title: Text(item.title),
subtitle: Text('${item.likes}'),
trailing: Icon(
item.like ? Icons.favorite : Icons.favorite_border,
color: item.like ? Colors.red : null,
),
//trailing: Checkbox(value: item.like, onChanged: null),
onTap: () {
setCompletness(item);
},
),
);
}
void addSong(Song item) {
setState(() {
list.add(item);
});
}
void setCompletness(Song item) {
setState(() {
item.like = !item.like;
});
item.like ? item.likes++ : item.likes--;
}
void checkSong(Song item) {
if (list.contains(item)) {
item.likes += 1;
} else {
addSong(Song(title: textfieldControllersong.text, like: false, likes: 0));
}
}
}```
【问题讨论】:
标签: flutter listview add flutter-web