Dio 在 Scroll Controller 侦听器中进行多次 API 调用

Dio Makes Many API calls in Scroll Controller listener

我使用 Dio 在滚动控制器中调用 APIs,我期待 1 个 http 调用,但它无缘无故地调用了大约 80 次..

代码:

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

这是日志:

    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 ...

正如您在日志中看到的那样,“FIRED”只写了 2 次,这没关系,但是“API CALLED”写了 80 次,有时甚至更多。

就是不知道为什么Dio.get打了大概80次

很抱歉回复你晚了。 问题出在您的 initState 中,意味着您正在对 addListener 进行嵌套连接。在 _scrollListener() 中,您已经将 addListener 附加到您的 ScrollController,然后您还调用 _scrollController.addListener(_scrollListener).

解决方案

您的代码有问题