2

我使用 Dio 在滚动控制器中调用 API,我期待 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 次

4

1 回答 1

1

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

解决方案

在此处输入图像描述

你的代码有问题

在此处输入图像描述

于 2021-07-28T21:48:27.310 回答