0

I have a problem while removing Movie from List. When i remove a movie from the list then all the element removed, the list becomes empty[].

Here is the List printed in the console:

[{id: 346698, title: Barbie, is_bookmark: false, poster_path: /iuFNMS8U5cb6xfzi51Dbkovj7vM.jpg, overview: Barbie and Ken are having the time of their lives in the colorful and seemingly perfect world of Barbie Land. However, when they get a chance to go to the real world, they soon discover the joys and perils of living among humans., release_date: 2023-07-19, rating: 7.498}, {id: 447365, title: Guardians of the Galaxy Vol. 3, is_bookmark: false, poster_path: /r2J02Z2OpNTctfOSN1Ydgii51I3.jpg, overview: Peter Quill, still reeling from the loss of Gamora, must rally his team around him to defend the universe along with protecting one of their own. A mission that, if not completed successfully, could quite possibly lead to the end of the Guardians as we know them., release_date: 2023-05-03, rating: 8.076}, {id: 872585, title: Oppenheimer, is_bookmark: false, poster_path: /8Gxv8gSFCU0XGDykEGv7zR1n2ua.jpg, overview: The story of J. Robert Oppenheimer’s role in the development of the atomic bomb d
W/ample.movie_hub(31376): Reducing the number of considered missed Gc histogram windows from 189 to 100

Here is the code that i use to remove movie from the list:

void removeMovie(List<Movie> bmMovies, int id) {
    for(int i=0; i<bmMovies.length; i++) {
       if(bmMovies[i].id == id) {
         bmMovies.removeAt(i);
         break;
       }
    }
  }

Can anyone tell me what i am doing wrong. And movies are rendering properly/correctly in the ui

1 Answers1

3

Why are you using the same variable in both loops?

In short: don't modify a list while iterating over it. See: Modifying list while iterating (Python)

Your fixed code should look like this:

 void removeMovie(List<Movie> movies, int id){
    for (int i = 0; i < movies.length; i++){
      if (movies[i].id == id){
        movies.removeAt(i);
        break;
      }
    }
  }

And an alternativ solution to your code would be to use the removeWhere method:

void removeMovie(List<Movie> bmMovies, int id) {
    bmMovies.removeWhere((movie) {
      return movie.id == id;
    });
  }
MendelG
  • 14,885
  • 4
  • 25
  • 52