Flutter web can't load network image from another domain

FlutterFlutter Web

Flutter Problem Overview


I can't load network images in flutter web from other domains with API calls. getting this error

> Trying to load an image from another domain? Find answers at: > https://flutter.dev/docs/development/platform-integration/web-images > ImageCodecException: Failed to load network image.

any help?

Flutter Solutions


Solution 1 - Flutter

For being able to display your images from any other Domain or from Firebase Storage on a Flutter web page you have to configure your data for CORS.

  1. Open the GCP console, select your project and start a cloud terminal session by clicking the >_ icon button in the top navbar.

  2. Click the open editor button (pencil icon), then create the cors.json file.

The cors.json file should look like this:

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

I set the origin to * which means that every website can display your images. But you can also insert the domain of your website there to restrict access.

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

If you need more information: https://cloud.google.com/storage/docs/configuring-cors

Solution 2 - Flutter

There are two ways to resolve this either run your app using HTML render or setup the CORS configuration.

1. Using HTML render

Taken from the docs

> CORS is a mechanism that browsers use to control how one site accesses the resources of another site. It is designed such that, by default, one web-site is not allowed to make HTTP requests to another site using XHR or fetch. This prevents scripts on another site from acting on behalf of the user and from gaining access to another site’s resources without permission > > When using <img>, <picture>, or <canvas>, the browser automatically blocks access to pixels when it knows that an image is coming from another site and the CORS policy disallows access to data.

Flutter has two renderers for web, canvaskit and html When you run/build app on the flutter web it uses renderers based on the device where its running.

HTML renderer: when the app is running in a mobile browser.

CanvasKit renderer: when the app is running in a desktop browser.

auto (default) - automatically chooses which renderer to use.

The HTML renderer can load cross-origin images without extra configuration. so you could use these commands to run and build the app.

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

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

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

2. Setup CORS Configuration
  • Download the Google-cloud-sdk which contains a tool called gsutil
  • In your flutter project create a file called cors.json and add this json file which will remove all domain restrictions.
[  {    "origin": ["*"],
    "method": ["GET"],
    "maxAgeSeconds": 3600
  }
]
  • Run gcloud init // located in google-cloud-sdk/bin
  • Authenticate yourself by clicking the link and choose the project in the console
  • finally execute gsutil cors set cors.json gs://<your-bucket-name>.appspot.com You can find your bucket name in firebase storage.

Solution 3 - Flutter

i solve this issue by using html renderer

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

or

flutter run --web-renderer html

Solution 4 - Flutter

for me flutter run -d chrome --web-renderer html worked.

Solution 5 - Flutter

If you use firebase storage just follow these steps:

  1. Open Google Cloud Console at your project
  2. Click on console icon in top right corner
  3. Click Open editor
  4. Click File->New->cors.json
  5. Place code below

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

  1. Then Run in console

**

> gsutil cors set cors.json gs://bucket-name

**

bucket-name is the name of the storage bucket which you can find on your firebase project above the folders in the storage section

Solution 6 - Flutter

To debug quickly, instead of flutter run -d chrome --web-renderer html running from the terminal you can also add the arguments --web-renderer html on your run config. On the menu bar, navigate through Run > Edit Configurations

Run config

Solution 7 - Flutter

If you can't update CORS settings or add proxy, prefer CanvasKit (has better performance) over HTML renderer - could display image with platform view:

import 'dart:html';
import 'package:flutter/material.dart';
import 'dart:ui' as ui;

class MyImage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    String imageUrl = "image_url";
    // https://github.com/flutter/flutter/issues/41563
    // ignore: undefined_prefixed_name
    ui.platformViewRegistry.registerViewFactory(
      imageUrl,
      (int _) => ImageElement()..src = imageUrl,
    );
    return HtmlElementView(
      viewType: imageUrl,
    );
  }
}


Solution 8 - Flutter

it seems it solved my issue by running flutter run --web-renderer html

Solution 9 - Flutter

just add cors.json in web folder

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

Solution 10 - Flutter

There is a two way to solve this issue :

1- Just run your flutter web with flutter run -d chrome --web-renderer html

But there is one problem when you renderer your canvas view to HTML view. So your all views like images, text, etc gone blurry(bad quality). If you sacrifice the quality so go on with the first solution.

  1. If you don't sacrifice quality so you need to add some code to your backend site I have done with node js you can use with yours.

> app.use(function(req, res, next) { > res.header("Access-Control-Allow-Origin", "*"); > res.header("Access-Control-Allow-Headers", > "Origin, X-Requested-With, Content-Type, Accept" > ); > next(); > });

So, I chose the second solution because I don't sacrifice quality. So I provide you with my backend screenshot for better understanding hope you found your solution.

Screenshot

Solution 11 - Flutter

For someone who uses Slim Framework, just create a .htaccess file on that folder for storing images and put this line of code

Header set Access-Control-Allow-Origin *

Solution 12 - Flutter

I had an issue while loading content from other domains which I don't have control over to change the cors settings from the server-side. I have found a work around for this problem.

STEP 1: go to C:\src\flutter\packages\flutter_tools\lib\src\web or navigate from your flutter root directory to flutter\packages\flutter_tools\lib\src\web.

STEP 2: open chrome.dart in your text editor.

STEP 3: add '--disable-web-security' under the like '--disable-extensions' as save the file.

STEP 4: run flutter clean in your project folder and run the app.

Hope this works for you.
I haven't tested my application in production yet. Adding this flag might also cause some security issues.

Solution 13 - Flutter

Verified answer is correct, Upvoted you man. Here's how I did it

enter image description here

Solution 14 - Flutter

Simply.. in your flutter (web/index.html) add this:

enter image description here

Solution 15 - Flutter

This official solution worked for me on Chrome only (Source). But I had to run it first every time.

flutter run -d chrome --web-renderer html

And disabling web security also worked (Source). But the browsers will show a warning banner.

But In case you are running on a different browser than Chrome (e.g. Edge) and you want to keep 'web security' enabled. You can change the default web renderer in settings in VS Code

> File ==> Preferences ==> Settings ==> Enter 'Flutter Web' in the Search Bar ==> Set the default web renderer to html

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAbel AyalewView Question on Stackoverflow
Solution 1 - FlutterJens BeckerView Answer on Stackoverflow
Solution 2 - FlutterMahesh JamdadeView Answer on Stackoverflow
Solution 3 - FlutterAbel AyalewView Answer on Stackoverflow
Solution 4 - FlutterMichael UhlenbergView Answer on Stackoverflow
Solution 5 - FlutterF-YView Answer on Stackoverflow
Solution 6 - FlutterOmattView Answer on Stackoverflow
Solution 7 - FlutterNutsView Answer on Stackoverflow
Solution 8 - Fluttercarlosx2View Answer on Stackoverflow
Solution 9 - FlutterElmasryView Answer on Stackoverflow
Solution 10 - FlutterHandyPawanView Answer on Stackoverflow
Solution 11 - FlutterNM NaufaldoView Answer on Stackoverflow
Solution 12 - FlutterCSRView Answer on Stackoverflow
Solution 13 - FlutterMuhammad BilalView Answer on Stackoverflow
Solution 14 - FlutterEhab RedaView Answer on Stackoverflow
Solution 15 - FlutterAli Ali El-DabaaView Answer on Stackoverflow