Dio Makes Many API calls in Scroll Controller listener

132

I'm sorry for responding you late. Problem is in your initState, means You are making nested attachment to the addListener. inside _scrollListener() you have already attached a addListener to your ScrollController, then you also call _scrollController.addListener(_scrollListener).

Solution

enter image description here

Problem with your code

enter image description here

Share:
132
Riki Raspoutine
Author by

Riki Raspoutine

Updated on December 31, 2022

Comments

  • Riki Raspoutine
    Riki Raspoutine over 1 year

    I used Dio to call APIs in scroll Controller , i was expecting 1 http call , but its calling about 80 times without any reason ..

    the code :

     int i=0;
    
     @override
     void initState() {
        super.initState();
        _scrollController.addListener(_scrollListener);
     }
    
     void _scrollListener() {
        _scrollController.addListener(() async {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        print("FIRED");
        var dio = new Dio();
        var url = "https://pokeapi.co/api/v2/pokemon?limit=20&offset=" + (20).toString();
        dio.get(url).then((response){
          setState(() {
            i++;
          });
          print("----------------------------------------------------"+i.toString()+"------------------------------------");
          print("API CALLED ...");
        });
      }
     });
    }
    

    and this is the log :

        I/flutter (10743): FIRED
        I/flutter (10743): FIRED
        I/flutter (10743): ----------------------------------------------------1------------------------------------
        I/flutter (10743): API CALLED ...
        I/flutter (10743): ----------------------------------------------------2------------------------------------
        I/flutter (10743): API CALLED ...
        I/flutter (10743): ----------------------------------------------------3------------------------------------
        I/flutter (10743): API CALLED ...
        I/flutter (10743): ----------------------------------------------------4------------------------------------
        I/flutter (10743): API CALLED ...
        I/flutter (10743): ----------------------------------------------------5------------------------------------
        I/flutter (10743): API CALLED ... 
        I/flutter (10743): ----------------------------------------------------6------------------------------------
        I/flutter (10743): API CALLED ...
        I/flutter (10743): ----------------------------------------------------80------------------------------------
        I/flutter (10743): API CALLED ...
    

    as you can see in the log , "FIRED" wrote only 2 times and that's OK , but "API CALLED" wrote 80 times , and sometimes even more .

    I just don't know why Dio.get called about 80 times