dart 如何在flutter webview上检测滚动结束?

vmdwslir  于 2023-06-03  发布在  Flutter
关注(0)|答案(3)|浏览(158)

我目前正在用flutter和webview开发一个移动应用程序。如何检测滚动当它到达一个网站页面在webview行的末尾?

qlzsbp2j

qlzsbp2j1#

我通过在Flutter端添加这个脚本解决了这个问题

WebView(
    initialUrl: "http://url.com/tos",
    javascriptMode: JavascriptMode.unrestricted,
    javascriptChannels: [
    JavascriptChannel(
        name: 'FLUTTER_CHANNEL',
        onMessageReceived: (message) {
            if (message.message.toString() ==
                "end of scroll") {
                setState((){ 
                    enableAgreeButton = true; 
                });
            }
        })
    ].toSet(),
    gestureNavigationEnabled: true,
    debuggingEnabled: true,
)

这个在js端

<script>
window.onscroll = function(ev) {
    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
    window.FLUTTER_CHANNEL.postMessage('end of scroll');
    }
};
</script>

感谢nsNeruno和 Redis 的洞察力

yv5phkfx

yv5phkfx2#

我遇到了同样的问题,所以我导入syncfusion_flutter_pdfviewer。您可以在此查看器上设置控制器并使用侦听器。
它可以通过JavaScript与webview来完成,但它有点复杂。

jmo0nnb3

jmo0nnb33#

使用webview_flutter(4.2.1),您可以将javascript通道添加到webview控制器并监听其上接收的消息。从webview你可以发送滚动进度信息到这个频道。在onMessageReceived中,您可以获得进度:

Future<void> fetchArticle() async {
    late final PlatformWebViewControllerCreationParams params;
    params = const PlatformWebViewControllerCreationParams();

    final WebViewController controller =
        WebViewController.fromPlatformCreationParams(params);

    controller
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..addJavaScriptChannel(
        'ARTICLE_SCROLL_CHANNEL',
        onMessageReceived: (progress) {
          setState(() {
            position = double.parse(progress.message) / 100;
          });
        },
      )
      ..setBackgroundColor(const Color(0x00000000))
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageFinished: (String url) {
            _controller.runJavaScript(
              '''
              window.addEventListener('scroll', function() {
                progress = (this.scrollY / ( document.body.scrollHeight - window.innerHeight ) ) * 100;
                window.ARTICLE_SCROLL_CHANNEL.postMessage(progress);
              });
              ''',
            );
          },
        ),
      )
      ..loadRequest(Uri.parse('https://flutter.dev'));

    _controller = controller;
  }

相关问题