Flutter. Check list if the new item title already exist. If not add the item to the list

Issue

I have a Flutter Website where i have a List with Songs. The user can add Songs to the List, i want to implement that after a user adds a new song the list gets checked if the Song already exists. If it already exists then the likes property from the existing item is increased. if it doesnt exists the item is added.

I tried it with list.contains(item.title) but it doesnt work properly.

Here is my code:

  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));
    }
  }
}```

Solution

Here you are comparing the two objects it may happen that the song 1 and song 2 has difference of space in it so you can iterate list of song and only compare titles or song name

bool isSongFound = false;
list.forEach((s){
  if(s.title.trim() == item.title.trim()){
    isSongFound=true;
  }
});
if(isSongFound){
  item.likes += 1;
}
else{
  addSong(Song(title: textfieldControllersong.text, like: false, likes: 0));
}

Answered By – Kaival Patel

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.