如何在flutter webview包中触发基于URL导航的事件

kuuvgm7e  于 6个月前  发布在  Flutter
关注(0)|答案(1)|浏览(63)

如何在flutter WebView中当用户导航到特定URL时显示snackbar
以及如何在webview中添加按钮以在webview内的页面之间导航

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Web view'),
      ),
      body: WebViewWidget(
        controller:   WebViewController()
      ..enableZoom(false)
      ..setNavigationDelegate(NavigationDelegate(
        onNavigationRequest: (request) {
          if (request.url.startsWith(widget.returnUrl)) {
            print("Hello");
            return NavigationDecision.prevent;
          }
          return NavigationDecision.navigate;
        },
      ))
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..loadRequest(
        Uri.parse('https://google.com/'),
      )
      )
    );
  }
}

字符串

0s7z1bwu

0s7z1bwu1#

解决方法:

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Web view'),
       leading: IconButton(
        onPressed: () {
          Navigator.of(context).pop();
        },
        icon: Icon(
          Icons.arrow_back,
          color: Theme.of(context).primaryColorDark,
        )),
      ),
      body: WebViewWidget(
      controller: WebViewController()
        ..enableZoom(false)
        ..setNavigationDelegate(NavigationDelegate(
          onNavigationRequest: (request) {
            if (request.url ==
                "https://docs.flutter.dev/get-started/install") {
              ScaffoldMessenger.of(context)
                  .showSnackBar(SnackBar(content: Text("Hello")));
              return NavigationDecision.prevent;
            }

            return NavigationDecision.navigate;
          },
        ))
        ..setJavaScriptMode(JavaScriptMode.unrestricted)
        ..loadRequest(
          Uri.parse('https://flutter.dev/'),
        ))
    );
  }
}

字符串
结果:

相关问题