如何在 Flutter Webview 中禁用远离初始 URL 的导航

Joh*_*oll 6 navigation webview flutter

我有一个 Flutter 应用程序,可以将网站加载到 WebView 小部件中。

有什么方法可以将该网络视图锁定到初始网站吗?我不希望用户能够离开此页面。

Sae*_*eed 3

在 a 中,StatefullWidget您可以放入这行代码:navigationDelegate在这种情况下起着关键作用。

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter Web View'),
        backgroundColor: AppColors.engenesisBlue,
      ),
      body: WebView(
        initialUrl: widget.url,
        javascriptMode: JavascriptMode.unrestricted,
        navigationDelegate: (NavigationRequest request) {
          print(request.url);
          setState(() => counter++);

          if (counter == 1) {
            return NavigationDecision.navigate;
          }
          return NavigationDecision.prevent;
        },
      ),
    );
  }
Run Code Online (Sandbox Code Playgroud)

Web 视图将拒绝导航两次。因此,页面加载后您将无法导航。