You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter的WebView中检测是否已滚动到页面底部?

解决WebView滚动行为检测问题

直接用Flutter的ScrollController没法检测WebView的滚动,因为WebView的滚动是由原生控件处理的,和Flutter的ScrollView不属于同一套体系。你可以试试下面两种实用方案:

方案一:通过WebViewController注入JS监听滚动

借助WebView控制器向页面注入JavaScript代码,监听网页自身的滚动事件,再将滚动状态回调给Flutter:

late WebViewController _webViewController;

// WebView初始化配置
WebView(
  initialUrl: "你的网页地址",
  onWebViewCreated: (controller) {
    _webViewController = controller;
    _injectScrollListener();
  },
  javascriptMode: JavascriptMode.unrestricted,
)

// 注入滚动监听的JS逻辑
void _injectScrollListener() {
  const jsCode = """
    window.addEventListener('scroll', function() {
      // 留20px误差避免布局精度问题导致判断不准
      const isBottom = (window.innerHeight + window.scrollY) >= document.body.offsetHeight - 20;
      window.flutter_inappwebview.callHandler('scrollHandler', isBottom);
    });
  """;
  _webViewController.runJavascript(jsCode);
  
  // 监听JS传回的滚动状态
  _webViewController.addJavaScriptChannel(
    'scrollHandler',
    onMessageReceived: (message) {
      bool reachedBottom = message.message == 'true';
      setState(() {
        _reachedBottom = reachedBottom;
      });
    },
  );
}

方案二:使用功能更完善的InAppWebView包

如果webview_flutter的功能满足不了需求,可以替换为flutter_inappwebview包,它自带原生的滚动监听API:

InAppWebView(
  initialUrlRequest: URLRequest(url: Uri.parse("你的网页地址")),
  onScrollChanged: (controller, x, y) async {
    final contentHeight = await controller.getContentHeight();
    final scrollViewHeight = controller.getScrollViewHeight();
    // 判断是否滚动至底部,留10px误差
    bool isBottom = (y + scrollViewHeight) >= contentHeight - 10;
    setState(() {
      _reachedBottom = isBottom;
    });
  },
)

注意:使用webview_flutter方案时,必须开启javascriptMode: JavascriptMode.unrestricted,否则注入的JS代码无法生效。

内容的提问来源于stack exchange,提问作者choi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 17:17:13