Flutter IFrameElement 不更改源

Soh*_*ail 1 flutter flutter-web

我创建了以下无状态小部件来在我的 Flutter WPA 中显示一些 Web 内容。它的父级是全状态的,并在_frameUrl更改时重建此小部件。但这只是第一次发生。之后,当父级更改时_frameUrl,我可以在日志中看到小部件正在重建并获得新的 URL,但它仍然使用第一次给出的旧 URL 重新加载。

import 'package:flutter/material.dart';
import 'dart:html';
import 'package:universal_ui/universal_ui.dart';

class HtmlFrame extends StatelessWidget {
  var _iframeElement;
  final String _frameUrl;

  HtmlFrame(this._frameUrl);

  @override
  Widget build(BuildContext context) {
    print("Frame build: $_frameUrl");

    _iframeElement = IFrameElement();
    _iframeElement.height = '500';
    _iframeElement.width = '500';
    _iframeElement.src = _frameUrl;
    _iframeElement.style.border = 'none';
    _iframeElement.allowFullscreen = true;

    // ignore: undefined_prefixed_name
    ui.platformViewRegistry.registerViewFactory(
      'iframeElement',
      (int viewId) => (_iframeElement as IFrameElement),
    );

    return HtmlElementView(
      key: UniqueKey(),
      viewType: 'iframeElement',
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

日志如下所示:

### First URL: https://www.google.com

Frame build: http://www.google.com
Refused to display 'https://www.google.com/' in a frame because it set 'X-Frame-Options' to 'sameorigin'.

### After giving it the second URL: https://www.bing.com

Frame build: https://www.bing.com/
Refused to display 'https://www.google.com/' in a frame because it set 'X-Frame-Options' to 'sameorigin'.
Run Code Online (Sandbox Code Playgroud)

我在上面的日志示例中使用了 google 和 bing,以显示它如何再次尝试加载第一个 URL,因为 Sameorigin 错误会记录它尝试的 URL。在我的应用程序中不存在这样的问题,并且 URL 属于允许的网站。

小智 9

只需在将 src url 注册到 ui 时提供动态名称即可。所以最好的方法和简单的方法就是在你的代码中传递 url 作为寄存器名称。

ui.platformViewRegistry.registerViewFactory(
  _frameUrl,
  (int viewId) => (_iframeElement as IFrameElement),
);

return HtmlElementView(
  key: UniqueKey(),
  viewType: _frameUrl,
);
Run Code Online (Sandbox Code Playgroud)

就是这样。