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?
They are different. NetworkImage class creates an object the provides an image from the src URL passed to it. It is not a widget and does not output an image to the screen. Image.network creates a widget that displays an image on the screen.
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.
Open the GCP console, select your project and start a cloud terminal session by clicking the >_
icon button in the top navbar.
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.
gsutil cors set cors.json gs://your-bucket
If you need more information: https://cloud.google.com/storage/docs/configuring-cors
There are two ways to resolve this either run your app using HTML render or setup the CORS configuration.
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
[ { "origin": ["*"], "method": ["GET"], "maxAgeSeconds": 3600 } ]
gcloud init
// located in google-cloud-sdk/bingsutil cors set cors.json gs://<your-bucket-name>.appspot.com
You can find your bucket name in firebase storage.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With