Flutterweb无法从另一个域加载网络图像

我无法通过 API 调用从其他域加载 flutter web 中的网络图像。收到这个错误

试图从另一个域加载图像?在以下位置找到答案:
https:
//flutter.dev/docs/development/platform-integration/web-images ImageCodecException:无法加载网络图像。

有什么帮助吗?

回答

为了能够在 Flutter 网页上显示来自任何其他域或 Firebase 存储的图像,您必须为CORS配置数据。

  1. 打开GCP 控制台,选择您的项目并通过单击>_顶部导航栏中的图标按钮启动云终端会话。

  2. 单击打开编辑器按钮(铅笔图标),然后创建cors.json文件。

cors.json文件应如下所示:

[
  {
    "origin": ["*"],
    "method": ["GET"],
    "maxAgeSeconds": 3600
  }
]

我将原点设置为*这意味着每个网站都可以显示您的图像。但是您也可以在那里插入您网站的域来限制访问。

  1. gsutil cors set cors.json gs://your-bucket

如果您需要更多信息:https : //cloud.google.com/storage/docs/configuring-cors

  • On Step 2, in order to create the cors.json file, click on the 3 dots (...) on the same row as Explorer:XXXX OR just click on File>new file. Step 3: You'll find "your-bucket" in your firebase STORAGE console and YOU WILL HAVE TO AUTHORIZE when you run the shell command.

回答

取自文档

CORS 是浏览器用来控制一个站点如何访问另一个站点资源的机制。它被设计为默认情况下不允许一个网站使用 XHR 或 fetch 向另一个网站发出 HTTP 请求。这可以防止另一个站点上的脚本代表用户执行操作并防止未经许可访问另一个站点的资源

使用 <img>、<picture> 或 <canvas> 时,当浏览器知道图像来自另一个站点并且 CORS 策略不允许访问数据时,它会自动阻止对像素的访问。

Flutter 有两个 Web 渲染器,canvaskit 和 html。当您在 Flutter Web 上运行/构建应用程序时,它使用基于运行设备的渲染器。

HTML 渲染器:当应用程序在移动浏览器中运行时。

CanvasKit 渲染器:当应用程序在桌面浏览器中运行时。

HTML 渲染器无需额外配置即可加载跨源图像。所以你可以使用这些命令来运行和构建应用程序。

flutter run -d chrome --web-renderer html // to run the app

flutter build web --web-renderer html --release // to generate a production build

来源:https : //flutter.dev/docs/development/tools/web-renderers


回答

为我flutter run -d chrome --web-renderer html工作。

  • But does it work in production?

回答

我通过使用 html 渲染器解决了这个问题

flutter build web --release --web-renderer html

或者

flutter run --web-renderer html


以上是Flutterweb无法从另一个域加载网络图像的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>