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

359

Solution 1

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

Solution 2

Alright i fixed the issue myself. I tried to increase the likes from the wrong Song ups, beginner mistake. Anyway here is the finished code.

void checkSong(Song item) {
    bool isSongFound = false;
    list.forEach((s) {
      if (s.title.trim() == item.title.trim()) {
        setState(() {
          s.likes++;
        });
        isSongFound = true;
      }
    });
    if (!isSongFound) {
      addSong(Song(title: textfieldControllersong.text, like: false, likes: 0));
    }
  }
Share:
359
Rashorr
Author by

Rashorr

Updated on December 28, 2022

Comments

  • Rashorr
    Rashorr over 1 year

    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));
        }
      }
    }```
    
  • Rashorr
    Rashorr about 3 years
    Thanks for the answer! The item doesnt gets added, so the comparing works. But if isSongFound is true item.likes +=1 doesnt work. Maybe i have to say exactly which song the likes should be increased from. But on the other Hand I give the function the exact Song
  • Kaival Patel
    Kaival Patel about 3 years
    You can upvote the answer but this is not efficient pls check the two instances of the song you are comparing and it is good habit to trim the textfield input as single space can create the mess.And yeah you have to do setState I guess to reflect into the UI, see it and let me know if any error persist
  • Rashorr
    Rashorr about 3 years
    Why is it not efficient? I already tried to set it into set state like this: if (isSongFound) { setState(() { item.likes++; }); but this didnt work either, i can compile it without any errors, but the like value does net get increased after adding a Song with the same title.
  • Kaival Patel
    Kaival Patel about 3 years
    Not efficient because you are iterating the list of songs every time with single title you are trying to match.