1

What I'm trying to achieve

I'm trying to generate a list from json data and append the next page data to the current list, when scrollcontroller reaches the bottom.

Problem

The items are generated when scrollcontroller hits the bottom but it's also adding some previous element into the List and randomly making duplicate items

E.g: https://streamable.com/5n01f

MY CODE

    List<MovieJson> movielist = [];

  ScrollController _scrollController = new ScrollController();
  int pageindex = 1;
  _MoviePageState() {
    fetchdata(pageindex);
  }

  void initState() {
    super.initState();

 //SCROLLCONTROLLER LOGIC

    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        pageindex += 1;
        print(_scrollController.position.pixels.toString());
        setState(() {
          fetchdata(pageindex);
        });
      }
    });
  }

  Future<List<MovieJson>> fetchdata(int index) async {

    final response = await http.get('${tmdb.url_v3}' +
        'trending/movie/week' + //path_param
        '?' + //query_string_options
        '${tmdb.api_key_url}' + //api_key=api_key
        '&page=' + //page
        '$index');

    final jsonData = json.decode(response.body);
    for (var item in jsonData['results']) {
      MovieJson movie = MovieJson.fromJson(item);
      movielist.add(movie);
    }
    return movielist;
  }

Rest of the code is building a ListView with FutureBuild Should I add that too?

Nadeem Siddique
  • 1,988
  • 4
  • 14
  • 20

1 Answers1

0

You need to check whether the movie already exists in the list before adding it.

if(!movielist.contains(movie))
  movielist.add(movie);
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
Mayank Kumar Chaudhari
  • 16,027
  • 10
  • 55
  • 122
  • just as an alert, this `contains` will only work if `MovieJson` has overrided the `==` operator (and maybe `hashCode` too). ([check this related answer](https://stackoverflow.com/a/52482866/796963)) – Feu Dec 08 '18 at 15:11