首页 > 解决方案 > Flutter webview navigationDelegate 调用了两次

问题描述

我正在尝试使用 Flutter Web 视图下载包含特定 url 模式的文件。这可行,但在这种情况下,浏览器打开了两次,因为 navigationDelegate 被调用了两次。isForMainFrameNavigationRequest 对象除了属性是相同的。第一次是假的,第二次是真的。

CupertinoPageScaffold(
  navigationBar: CupertinoNavigationBar(middle: Text(_appTitle)),
  child: Container(
    child: SafeArea(
      child: IndexedStack(
        index: _stackToView,
        children: <Widget>[
          WebView(
            key: _key,
            javascriptMode: JavascriptMode.unrestricted,
            initialUrl: this._connectionString,
            onPageStarted: (value) => setState(() {
              if (shouldChangeStack) {
                _stackToView = 1;
              } else {
                _stackToView = 0;
              }

            }),
            onPageFinished: (value) => setState(() {
              _stackToView = 0;
            }),
            navigationDelegate: (NavigationRequest request) async {
              print(request.url);
              if (request.url.contains("download")) {
                setState(() {
                  shouldChangeStack = false;
                });
                if (await canLaunch(request.url)) {
                  await launch(request.url);
                }
                return NavigationDecision.prevent;
              } else {
                setState(() {
                  shouldChangeStack = true;
                });
                return NavigationDecision.navigate;
              }
            },
          ),
          Container(
            child: Center(
              child: CircularProgressIndicator(),
            ),
          )
        ],
      ),
      top: true,
    ),
  ),
);

标签: iosflutter

解决方案


委托方法被调用两次的原因是因为setState()被调用。这会导致整体Widget build()被重建。正如前面在评论中提到的,解决此问题的方法是在启动页面之前设置检查器并定义是否需要打开页面。


推荐阅读