How to handle Image.network
when the url is wrong or the destination leads to 404.
for example try
Image.network('https://image.tmdb.org/t/p/w92')
asked Sep 29, 2018 at 13:36
mohamed zayanimohamed zayani
8431 gold badge6 silver badges10 bronze badges
1
I have handled the network image issue related to 404 by using an errorBuilder.
Image.network('Your image url...',
errorBuilder: (BuildContext context, Object exception, StackTrace stackTrace) {
return Text('Your error widget...');
},
),
errorBuilder property
answered Oct 26, 2020 at 5:07
6
UPDATE: Look at the new accurate way which uses an inbuilt method, answered by @Niraj Phutane here which requires no plugins.
outdated old answer (before errorbuilder existed)
I recommend using cached_network_image which gives an option to add a placeholder image and also an error widget in case of a 404 or 403.
CachedNetworkImage(
imageUrl: "http://via.placeholder.com/350x150",
placeholder: (context, url) => new CircularProgressIndicator(),
errorWidget: (context, url, error) => new Icon(Icons.error),
),
answered Jun 9, 2019 at 10:24
Phani RithvijPhani Rithvij
3,7933 gold badges26 silver badges54 bronze badges
4
You can display image from assets when you found 404 or any other error while loading image.
What I have done is:
FadeInImage(
image: NetworkImage("imageUrl"),
placeholder: AssetImage(
"assets/images/placeholder.jpg"),
imageErrorBuilder:
(context, error, stackTrace) {
return Image.asset(
'assets/images/error.jpg',
fit: BoxFit.fitWidth);
},
fit: BoxFit.fitWidth,
)
Check imageErrorBuilder
property.
Dharman♦
29.3k21 gold badges80 silver badges131 bronze badges
answered Feb 12, 2021 at 7:07
Pratik ButaniPratik Butani
59.2k55 gold badges266 silver badges428 bronze badges
1
Can use errorBuilder from Image.network or Image.asset
Image.network(
path.image,
width: 40,
height: 40,
errorBuilder: (BuildContext context, Object exception,
StackTrace? stackTrace) {
return const Text('😢');
},
answered Feb 17, 2022 at 2:55
You can use ImageStream
to handle errors.
class CustomProductImage extends StatefulWidget {
final String image;
const CustomProductImage(this.image);
@override
State<CustomProductImage> createState() => _CustomProductImageState();
}
class _CustomProductImageState extends State<CustomProductImage> {
Widget mainWidget = const CircularProgressIndicator(); // Placeholder widget
@override
void initState() {
super.initState();
Image image = Image.network(widget.image, width: 50, height: 50);
final ImageStream stream = image.image.resolve(ImageConfiguration.empty);
stream.addListener(ImageStreamListener((info, call) {
if (!completer) {
completer = true;
setState(() {
mainWidget = image;
});
}
}, onError: (dynamic exception, StackTrace? stackTrace) {
print('Error is $exception , stack is $stackTrace');
setState(() {
mainWidget = const Icon(Icons.error); // Error Widget
});
}));
}
@override
Widget build(BuildContext context) {
return mainWidget;
}
}
answered Jul 28, 2020 at 10:26
BIS TechBIS Tech
15.3k10 gold badges84 silver badges135 bronze badges
4
It’s weird but you can’t easily handle errors correctly with Image.Provider.
Use this handy package: https://pub.dev/packages/flutter_advanced_networkimage
Then in you code:
backgroundImage: AdvancedNetworkImage(
"YOUR IMAGE URL",
fallbackAssetImage: "YOUR DEAULT ASSERT IMAGE eg:assets/default.png"
)
answered May 31, 2020 at 1:40
2
I had the same problem, but, I solved it using the property ‘imageErrorBuilder’ of the FadeInImage class.
Here is a link about that: https://api.flutter.dev/flutter/widgets/Image/errorBuilder.html
The example was made for Image.network(), but it also work for FadeInImage.
Here’s my code:
FadeInImage(
imageErrorBuilder: (BuildContext context, Object exception, StackTrace stackTrace) {
print('Error Handler');
return Container(
width: 100.0,
height: 100.0,
child: Image.asset('assets/img/no_disponible.jpg'),
);
},
placeholder: AssetImage('assets/img/loading.gif'),
image: NetworkImage(product.getImg()),
fit: BoxFit.cover,
height: 100.0,
width: 100.0,
),
The function of imageErrorBuilder will be execute for example, if the direction of the page doesn’t exist.
I’m using Flutter 1.20.1
answered Sep 7, 2020 at 4:57
1
I used the basic Image widget and added an error builder for errors and a loadingBuilder for loading status and for the actual image I used NetworkImageWithRetry so that it will try to load the image many times and give you an error at the end if it couldn’t load the image.
Image(
image: NetworkImageWithRetry(
'http://ImageUrl.png',),
errorBuilder: (context, exception, stackTrack) => Icon(Icons.error,),
loadingBuilder: (context, exception, stackTrack) => CircularProgressIndicator(),
)
answered Apr 18, 2021 at 8:48
2
For those who are using firebase storage
The above methods didn’t help me at all.
When the object is not found in firebase, I got an exception "Null is not a type of List<int>"
.
So I decided to verify if the Unit8List values are valid or not.
If it’s valid then we are ready to show the image otherwise use any widgets as placeholder.
Future<String?> getImgUrl()async{
//Storage structre: avatars/+919999999999/avatar.jpg
//Permanent url of an image without tokens
//%2F means "/"
//%2B mans "+"
String imgUrl = "https://firebasestorage.googleapis.com/v0/b/yourFIrebaseProjectID/o/avatars%2F%2B919999999999%2Favatar.jpg?alt=media";
try {
Uint8List bytes = (await NetworkAssetBundle(Uri.parse(imgUrl)).load(imgUrl)).buffer.asUint8List();
print("The image exists!");
return imgUrl;
} catch (e) {
print("Error: $e");
return null;
}
}
Widget futureBulder(){
return FutureBuilder(
future: getImgUrl(),
builder: (BuildContext context, AsyncSnapshot<String?> snapshot) {
bool error = snapshot.data==null;
//I use NetworkImage for demonstration purpose, use it whatever widget u want
return CircleAvatar(
backgroundImage: error? null : NetworkImage(snapshot.data!),
);
},
);
}
answered Nov 21, 2021 at 3:45
RajeshRajesh
3,4046 gold badges23 silver badges42 bronze badges
4
I ran into this problem while learning flutter (not web). I found the solution after I tried all the non-working options that are given in this thread. They all print errors to the console if the address is wrong or the resource is not found. To play with my solution, you will need to install two plugins: http and url_launcher (the second plugin is only needed to open a link to this topic in the simulator). Be sure to read the up-to-date instructions for using plugins. How to play, you ask? Change the address in input Image URL field as you like! Please report bugs if you find them.
import 'package:http/http.dart' as http;
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Image 404',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
static const _problemDescriptionUrl =
'https://stackoverflow.com/questions/52568872/flutter-how-to-handle-image-network-error-like-404-or-wrong-url';
String imageUrl =
'https://repository-images.githubusercontent.com/90528830/018a6400-d879-11e9-92b4-492c61d9bc32';
late Future<Widget> futureWidget;
Future<Widget> fetchImage() async {
if (imageUrl.startsWith('https://') &&
Uri.tryParse(imageUrl) != null &&
Uri.tryParse(imageUrl)!.hasAbsolutePath) {
final response = await http.get(Uri.parse(imageUrl));
if (response.statusCode == 200 &&
(response.headers.keys.contains('content-type') &&
!response.headers['content-type']!.contains('text/html'))) {
// If the server did return a 200 OK response,
// then parse the data.
return Image.memory(response.bodyBytes, fit: BoxFit.cover);
} else {
// If the server did not return a 200 OK response,
// then
return const Text('Failed to load Image');
}
}
return const Text('Failed to load Image');
}
@override
void initState() {
futureWidget = fetchImage();
super.initState();
}
void _launchUrl() async {
if (!await launchUrl(Uri.tryParse(_problemDescriptionUrl)!)) {
throw 'Could not launch $_problemDescriptionUrl';
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Image.network Error 404 Solution'),
),
body: Column(
children: [
TextButton(
onPressed: _launchUrl,
child: const Text('The problem described here')),
Container(
padding: const EdgeInsets.all(8),
alignment: Alignment.center,
width: double.infinity,
height: 200,
child: FutureBuilder<Widget>(
future: futureWidget,
builder: (context, snapshot) {
if (snapshot.hasData) {
return snapshot.data!;
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
),
),
Form(
child: TextFormField(
decoration: const InputDecoration(labelText: 'Image URL'),
initialValue: imageUrl,
maxLines: 3,
keyboardType: TextInputType.url,
textInputAction: TextInputAction.done,
onChanged: (val) {
setState(() {
imageUrl = val;
futureWidget = fetchImage();
});
},
),
)
],
),
);
}
}
answered Jul 12, 2022 at 19:48
I have implemented this StatefulWidget for the same case, hope this helps!!!
class NetworkImageHandlerViewer extends StatefulWidget {
final String imageURL;
bool errorFoundInImageLoad = false;
NetworkImageHandlerViewer({
Key key,
@required this.imageURL,
}) : super(key: key);
@override
_NetworkImageHandlerViewerState createState() =>
_NetworkImageHandlerViewerState();
}
class _NetworkImageHandlerViewerState extends State<NetworkImageHandlerViewer> {
@override
Widget build(BuildContext context) {
return Column(
children: [
Container(
height: 200,
// height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
// color: Colors.black,
child: (widget.errorFoundInImageLoad)
? Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Unable To Fetch Image",
),
IconButton(
iconSize: 40,
onPressed: () {
setState(() {
if (mounted) {
print("reloading image again");
setState(() {
widget.errorFoundInImageLoad = false;
});
}
});
},
icon: Icon(Icons.refresh),
),
Text(
"Tap Refresh Icon To Reload!!!",
),
],
)
: Image.network(
// widget.question.fileInfo[0].remoteURL,
widget.imageURL,
//
loadingBuilder: (context, child, loadingProgress) =>
(loadingProgress == null)
? child
: Center(
child: CircularProgressIndicator(),
),
errorBuilder: (context, error, stackTrace) {
Future.delayed(
Duration(milliseconds: 0),
() {
if (mounted) {
setState(() {
widget.errorFoundInImageLoad = true;
});
}
},
);
return SizedBox.shrink();
},
),
),
SizedBox(height: 25),
],
);
}
}
answered Jun 25, 2021 at 21:59
https://pub.dev/packages/extended_image
the plugin makes it easy to handle errors in Network image load
import 'package:flutter/material.dart';
import 'package:extended_image/extended_image.dart';
class ImageHolder extends StatefulWidget {
const ImageHolder(
{Key? key,
required this.url,
required this.imageHeight,
required this.imageWidth})
: super(key: key);
final String url;
final double imageHeight;
final double imageWidth;
@override
_ImageHolderState createState() => _ImageHolderState();
}
class _ImageHolderState extends State<ImageHolder>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
@override
void initState() {
_controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 3),
lowerBound: 0.0,
upperBound: 1.0);
super.initState();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return ExtendedImage.network(
widget.url,
fit: BoxFit.contain,
cache: true,
loadStateChanged: (ExtendedImageState state) {
switch (state.extendedImageLoadState) {
case LoadState.loading:
_controller.reset();
return Image.asset(
'assets/images/loading.gif',
fit: BoxFit.fill,
);
case LoadState.completed:
_controller.forward();
return FadeTransition(
opacity: _controller,
child: ExtendedRawImage(
image: state.extendedImageInfo?.image,
width: widget.imageWidth,
height: widget.imageHeight,
),
);
case LoadState.failed:
_controller.reset();
state.imageProvider.evict();
return Image.asset(
'assets/images/failed.jpg',
);
}
},
);
}
}
answered Jul 28, 2021 at 21:14
Javeed IshaqJaveed Ishaq
5,3885 gold badges34 silver badges57 bronze badges
CachedNetworkImage(
placeholder: (context, url) =>
Center(child: new CircularProgressIndicator()),
errorWidget: (context, url, error) =>
Icon(Icons.error),
imageUrl: image,
fit: BoxFit.fill,
)
answered Nov 1, 2021 at 15:47
1
there what i was looking for, but its temporary… its ignore 404 error exception and returning null.
FlutterError.onError = (FlutterErrorDetails details) {
if (details.library == 'image resource service') {
return;
}
FirebaseCrashlytics.instance.recordFlutterFatalError(details);
};
for more information
errorBuilder throws exception for invalid image data #107416
Fedor
15.1k7 gold badges38 silver badges114 bronze badges
answered Jan 30 at 8:31
This article shows you how to handle error network images in Flutter.
![](https://www.kindacode.com/wp-content/uploads/2020/10/Screen-Shot-2020-10-24-at-16.14.21.jpg?ezimgfmt=rs%3Adevice%2Frscb5-1)
If you use Image.network() to display an online image and that image is broken (404 not found, 403 forbidden, etc.), you can use the errorBuilder property to render something instead, such as a default image, text…
Example
This code snippet produces the app that is displayed in the screenshot above:
SizedBox(
width: double.infinity,
height: 300,
child: Image.network(
'https://www.kindacode.com/no-image.jpg', // this image doesn't exist
fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) {
return Container(
color: Colors.amber,
alignment: Alignment.center,
child: const Text(
'Whoops!',
style: TextStyle(fontSize: 30),
),
);
},
),
),
Complete source code (including boilerplate):
// kindacode.com
// main.dart
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
// hide debug banner
debugShowCheckedModeBanner: false,
title: 'KindaCode.com',
home: KindaCodeDemo(),
);
}
}
class KindaCodeDemo extends StatefulWidget {
const KindaCodeDemo({super.key});
@override
State<KindaCodeDemo> createState() => _KindaCodeDemoState();
}
class _KindaCodeDemoState extends State<KindaCodeDemo> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('KindaCode.com'),
),
body: SizedBox(
width: double.infinity,
height: 300,
child: Image.network(
'https://www.kindacode.com/no-image.jpg', // this image doesn't exist
fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) {
return Container(
color: Colors.amber,
alignment: Alignment.center,
child: const Text(
'Whoops!',
style: TextStyle(fontSize: 30),
),
);
},
),
),
);
}
}
I hope this helps.
Further reading:
- Flutter: Create a Password Strength Checker from Scratch
- Flutter: Caching Network Images for Big Performance gains
- Flutter: Reading Bytes from a Network Image
- Flutter: Set an image Background for the entire screen
- Flutter: Display Text over Image without using Stack widget
- Flutter: Drawing an N-Pointed Star with CustomClipper
You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Closed
antakuznet opened this issue
Dec 29, 2020
· 38 comments
Labels
in triage
Presently being triaged by the triage team.
Comments
After latest update I’m unable to show some network images on the web platform. Everything works just fine on Android.
This is error message:
════════════════════Exception caught by image resource service ════════════════════════════
The following ProgressEvent$ object was thrown resolving an image codec:
[object ProgressEvent]
When the exception was thrown, this was the stack
Image provider: NetworkImage(«https://firebasestorage.googleapis.com/v0/b/jetsea.appspot.com/o/yahts%2Fyaht.png?alt=media&token=dc4c2a5f-655c-4317-be80-68d6580c5a99», scale: 1)
Image key: NetworkImage(«https://firebasestorage.googleapis.com/v0/b/jetsea.appspot.com/o/yahts%2Fyaht.png?alt=media&token=dc4c2a5f-655c-4317-be80-68d6580c5a99», scale: 1)
═════════════════════════════════════════════════════════════════════════════
flutter doctor -v
[✓] Flutter (Channel dev, 1.26.0-1.0.pre, on macOS 11.1 20C69 darwin-x64, locale en-US)
• Flutter version 1.26.0-1.0.pre at /Users/antonkuznetsov/development/tools/flutter
• Framework revision 63062a6 (2 weeks ago), 2020-12-13 23:19:13 +0800
• Engine revision 4797b06
• Dart version 2.12.0 (build 2.12.0-141.0.dev)
[✓] Android toolchain — develop for Android devices (Android SDK version 29.0.2)
• Android SDK at /Users/antonkuznetsov/Library/Android/sdk
• Platform android-30, build-tools 29.0.2
• Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b4-5784211)
• All Android licenses accepted.
[✓] Xcode — develop for iOS and macOS (Xcode 12.3)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 12.3, Build version 12C33
• CocoaPods version 1.10.0.rc.1
[✓] Chrome — develop for the web
• Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
[✓] Android Studio (version 3.6)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin version 45.1.1
• Dart plugin version 192.7761
• Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b4-5784211)
[✓] VS Code (version 1.52.1)
• VS Code at /Applications/Visual Studio Code.app/Contents
• Flutter extension version 3.18.0
[✓] Connected device (2 available)
• Pixel 5 (mobile) • 0A211FDD4006JF • android-arm64 • Android 11 (API 30)
• Chrome (web) • chrome • web-javascript • Google Chrome 87.0.4280.88
• No issues found!
Hi @antakuznet
Can you please provide a minimal complete reproducible code sample?
Thank you
Hi @pedromassangocode
Thank you for the reply. Here is my code:
Code
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Test Image', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Test Image'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Image.network( 'https://images.pexels.com/photos/462118/pexels-photo-462118.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500', width: 100, height: 100, ), Image.network( 'https://firebasestorage.googleapis.com/v0/b/jetsea.appspot.com/o/jets%2Fjetski.png?alt=media&token=f93b2680-6f03-4ba1-b1f5-17beb0df6648', width: 100, height: 100, ), Image.network( 'https://github.com/flutter/plugins/raw/master/packages/video_player/video_player/doc/demo_ipod.gif?raw=true', width: 100, height: 100, ), ], ), ), ); } }
Hi @antakuznet
I cannot reproduce this issue either in dev nor master channel.
flutter doctor
[✓] Flutter (Channel dev, 1.26.0-1.0.pre, on Mac OS X 10.15.7 19H2 darwin-x64, locale en)
• Flutter version 1.26.0-1.0.pre at /Users/pedromassango/dev/SDKs/flutter_dev
• Framework revision 63062a6443 (3 weeks ago), 2020-12-13 23:19:13 +0800
• Engine revision 4797b06652
• Dart version 2.12.0 (build 2.12.0-141.0.dev)
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
• Android SDK at /Users/pedromassango/Library/Android/sdk
• Platform android-30, build-tools 30.0.2
• Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
• All Android licenses accepted.
[✓] Xcode - develop for iOS and macOS (Xcode 12.1)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 12.1, Build version 12A7403
• CocoaPods version 1.9.3
[✓] Chrome - develop for the web
• Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
[✓] Android Studio (version 4.1)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin can be installed from:
🔨 https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
🔨 https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
[✓] IntelliJ IDEA Community Edition (version 2020.3)
• IntelliJ at /Applications/IntelliJ IDEA CE.app
• Flutter plugin version 52.1.5
• Dart plugin version 203.5981.152
[✓] VS Code (version 1.51.1)
• VS Code at /Applications/Visual Studio Code.app/Contents
• Flutter extension version 3.16.0
[✓] Connected device (3 available)
• iPhone 12 Pro (mobile) • 1EEFA5B2-DA95-49CC-AA0B-968BB248B8F3 • ios • com.apple.CoreSimulator.SimRuntime.iOS-14-1 (simulator)
• macOS (desktop) • macos • darwin-x64 • Mac OS X 10.15.7 19H2 darwin-x64
• Chrome (web) • chrome • web-javascript • Google Chrome 87.0.4280.88
• No issues found!
Process finished with exit code 0
I’m also experiencing this error accessing images stored in MS Azure Blob storage.
I also saw this false behavior in Chrome (web-javascript) but it was always working on an Android device.
This bug happened after «git pull» my project on a different Computer.
When I type «flutter run» in the Terminal Window everything works as expected.
When I use the VSC Menu entry «Run»->… the error happens.
After some time the problem disappears but I don’t know why or what was the reason.
I am also facing this issue when trying to load my youtube videos’ thumbnail images using youtube data API, the images load on the emulator but not chrome.
oddly enough, when i run my project using the commande «fluuter run» it works and the images load just fine. still not the case when using VScode.
Having the same issue. I’m on beta channel
.
════════ Exception caught by image resource service ════════════════════════════
The following ProgressEvent$ object was thrown resolving an image codec:
[object ProgressEvent]
When the exception was thrown, this was the stack
Image provider: NetworkImage("https://github.com/Imgkl/FlikiPedia/blob/master/implementation.png", scale: 1)
Image key: NetworkImage("https://github.com/Imgkl/FlikiPedia/blob/master/implementation.png", scale: 1)
════════════════════════════════════════════════════════════════════════════════
code:
class FlikipediaApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Image.network(
"https://github.com/Imgkl/FlikiPedia/blob/master/implementation.png",
height: 500,
fit: BoxFit.contain,
);
}
}
Flutter doctor:
gokul@Kirans-MacBook-Pro-3 Imgkl.github.io % flutter devices
1 connected device:
Chrome (web) • chrome • web-javascript • Google Chrome 87.0.4280.141
• Error: Gokul’s iPhone is not connected. Xcode will continue when Gokul’s iPhone is connected. (code -13)
gokul@Kirans-MacBook-Pro-3 Imgkl.github.io % flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, 1.25.0-8.3.pre, on macOS 11.1 20C69 darwin-x64, locale en-IN)
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
[✓] Xcode - develop for iOS and macOS
[✓] Chrome - develop for the web
[✓] Android Studio (version 4.1)
[✓] IntelliJ IDEA Ultimate Edition (version 2019.1.3)
[✓] VS Code (version 1.52.1)
[✓] Connected device (1 available)
! Error: Gokul’s iPhone is busy: Waiting for Device. Xcode will continue when Gokul’s iPhone is finished. (code -10)
• No issues found!
It just happened to me. I also run a build online and it has no issues at all. Very odd. Any idea why this is happening. I did however upgraded my flutter the day before.
I would like to confirm that running flutter run solves the issue for me. Very strange.
To future readers,
It appears that this issue seems to be specific to VS Code. Run the app, through the terminal with the command flutter run
. Everything seems to be working fine.
- Hot restart, enter
r
- Hot reload, enter
R
Without additional information, we are unfortunately not sure how to resolve this issue. We are therefore reluctantly going to close this bug for now. Please don’t hesitate to comment on the bug if you have any more information for us; we will reopen it right away!
Thanks for your contribution.
Why is this issue not yet resolved?
I’m also having this issue, any solution?
I am having same issue
Another exception was thrown: ImageCodecException: Failed to load network image.
Same for me with Firebase Image or AWS S3
The following ImageCodecException was thrown resolving an image codec:
Failed to load network image.
Image URL: https://layouceferie.s3.eu-west-2.amazonaws.com/feminity.png
Trying to load an image from another domain? Find answers at:
https://flutter.dev/docs/development/platform-integration/web-images
When the exception was thrown, this was the stack
Image provider: NetworkImage("https://layouceferie.s3.eu-west-2.amazonaws.com/feminity.png", scale: 1)
Image key: NetworkImage("https://layouceferie.s3.eu-west-2.amazonaws.com/feminity.png", scale: 1)
when I click on the link it’s seem that we cannot load image from another domains
Same problem for me ? any update for this issue ?
Could anyone facing this issue provide flutter doctor -v
, a minimal code sample that reproduce the issue along with the steps to reproduce it?
Thank you
In my case I solved issues with network images from firebase storage by setting up CORS on a bucket with files. The best way to set it up is to create .json file with config:
[
{
«origin»: [«*»],
«method»: [«GET», «POST»],
«responseHeader»: [«Content-Type», «Access-Control-Allow-Origin», «Access-Control-Allow-Headers»],
«maxAgeSeconds»: 7200
}
]
and then use gsutil to set it up:
gsutil cors set ‘path to .json’ ‘bucket’
It solved problems with all images from my firebase storage. Also you can limit access to the files by specifying allowed «origin» in the .json file.
I have the same issue please help 😕
For future reference, VSCode specific bugs should be filed in the Dart-Code repo.
Issue filed here: Dart-Code/Dart-Code#3176
The last few comments look like #73327 to me, which is a CORS issue. It might be affected by the web renderer being used (which might cause it to occur from VS Code but not from the terminal if you’re not passing the same web-renderer.. VS Code passes --web-renderer=auto
by default) (see #73327).
I’m also facing this issue. Can’t load any images, not firebase or any other hosted image.
Tried running through terminal as suggested and still the same problem.
This comment has been minimized.
This would be a fix when you have control over your image server or cdn.
What if we dont have access to the server. I think it should be done in flutter?
Tho flutter run -d chrome --web-renderer html
works but not with canvaskit
.
↑I really am confused to be mentioned my issue.
How do I erase that?
To future readers,
It appears that this issue seems to be specific to VS Code. Run the app, through the terminal with the commandflutter run
. Everything seems to be working fine.* Hot restart, enter `r` * Hot reload, enter `R`
This did the trick
Could anyone facing this issue provide
flutter doctor -v
, a minimal code sample that reproduce the issue along with the steps to reproduce it?
Thank you
Same issue I faced today:
flutter doctor -v :
[√] Flutter (Channel stable, 2.0.2, on Microsoft Windows [Version 10.0.19041.867], locale en-IN)
• Flutter version 2.0.2 at C:Program Filesflutter
• Framework revision 8962f6d (13 days ago), 2021-03-11 13:22:20 -0800
• Engine revision 5d8bf81
• Dart version 2.12.1
[√] Android toolchain — develop for Android devices (Android SDK version 30.0.3)
• Android SDK at C:UsersSamarjeetAppDataLocalAndroidsdk
• Platform android-30, build-tools 30.0.3
• Java binary at: C:Program FilesAndroidAndroid Studiojrebinjava
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)
• All Android licenses accepted.
[√] Chrome — develop for the web
• Chrome at C:Program FilesGoogleChromeApplicationchrome.exe
[√] Android Studio (version 4.1.0)
• Android Studio at C:Program FilesAndroidAndroid Studio
• Flutter plugin can be installed from:
https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)
[√] VS Code (version 1.54.3)
• VS Code at C:UsersSamarjeetAppDataLocalProgramsMicrosoft VS Code
• Flutter extension version 3.20.0
[√] Connected device (2 available)
• Chrome (web) • chrome • web-javascript • Google Chrome 89.0.4389.90
• Edge (web) • edge • web-javascript • Microsoft Edge 89.0.774.57
• No issues found!
code sample:
Container(
child:
Image.network(imagepath, width: double.infinity),
),
I got this error in Android Studio as well. The «solution»: flutter run -d chrome —web-renderer html
works, but it sucks. Can you examine it and provide a better solution.
It is because canvaskit needs proper CORS policy. So if you want to use canvaskit you can’t load content from servers that do not let for that. If server is your you can configure proper CORS. When you use —web-renderer html browser do not use CORS policy.
I would like to use canvaskit but the only way I found is to use own server as proxy for loading these files
It is because canvaskit needs proper CORS policy. So if you want to use canvaskit you can’t load content from servers that do not let for that. If server is your you can configure proper CORS. When you use —web-renderer html browser do not use CORS policy.
I would like to use canvaskit but the only way I found is to use own server as proxy for loading these files
I can’t confirm that. My images are hosted in the Google Cloud (Firebase Storage) which I configured to allow all origins.
This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug, including the output of flutter doctor -v
and a minimal reproduction of the issue.
github-actions
bot
locked as resolved and limited conversation to collaborators
Aug 1, 2021
Labels
in triage
Presently being triaged by the triage team.
Hello friends, In today’s tutorial we would learn about errorBuilder inbuilt function of Image.network() widget in flutter. The errorBuilder function allows us to call any widget if in any circumstances the network image not found on server, returns 404 error, 403 forbidden error, deleted from the server and even if the image URL is broke. In easy works if our image is not load in the Image.network() widget then this function calls. So Now we can use this function as Backup function. Now what we’re doing in this tutorial is If our network image not found on server then it will show us a error image directly from local assets folder. So in this tutorial we would learn about Flutter Show Error Message When Network Image Not Found.
Contents in this project Flutter Show Error Message When Network Image Not Found :-
1. First of all we have to put the local Error image in the assets folder. So open your flutter project and make a folder named as assets.
2. Now inside the assets folder make another folder named as images.
3. Now download the Error Image from below. This Image is created by Myself so you can use it anywhere.
4. After downloading above image, Put the image inside assets/images folder.
5. Now in the next step, We have to put the assets/images folder path inside our project’s pubspec.yaml file. So open pubspec.yaml file present inside your flutter project in Text editor, I’m using Visual Studio Code.
6. Put below code inside the pubspec.yaml file under flutter section.
Source code of my pubspec.yaml file after adding above code :-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
name: app2 description: A new Flutter project. publish_to: ‘none’ version: 1.0.0+1 environment: sdk: «>=2.15.1 <3.0.0» dependencies: flutter: sdk: flutter cupertino_icons: ^1.0.2 flutter_emoji: ^2.2.1+1 share: ^2.0.4 fluttertoast: ^8.0.8 shared_preferences: ^2.0.13 url_launcher: ^6.0.20 dev_dependencies: flutter_test: sdk: flutter flutter_lints: ^1.0.0 flutter: assets: — assets/images/ uses—material—design: true |
7. Now we’re good to go. Open your project’s main.dart file and import material.dart package.
import ‘package:flutter/material.dart’; |
8. Creating void main runApp() method, Here we would call our main MyApp class.
void main() => runApp(MyApp()); |
9. Creating MyApp extends StatelessWidget class.
class MyApp extends StatelessWidget { } |
10. Creating a String variable named as imageURL. We would assign our Image URL to this variable.
String imageURL = «https://flutter-examples.com/wp-content/uploads/2019/09/blossom.jpg»; |
11. Creating Widget Build area -> Here we would make our main Image.network() widget with errorBuilder function. If the image not found the it will automatically load the local image.
Image.network( imageURL, width: 300, height: 200, fit: BoxFit.contain, errorBuilder: (context, error, stackTrace) { return Image.asset(‘assets/images/image_not_found.png’, width: 300, height: 200, fit: BoxFit.contain); }, ), |
12. Complete source code for main.dart file :-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import ‘package:flutter/material.dart’; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { String imageURL = «https://flutter-examples.com/wp-content/uploads/2019/09/blossom.jpg»; @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: SafeArea( child: Center( child: Column( children: <Widget>[ const Text( ‘Show Error Image If Main Image NOT Found in Flutter’, style: TextStyle(fontSize: 24), textAlign: TextAlign.center, ), Image.network( imageURL, width: 300, height: 200, fit: BoxFit.contain, errorBuilder: (context, error, stackTrace) { return Image.asset(‘assets/images/image_not_found.png’, width: 300, height: 200, fit: BoxFit.contain); }, ), ], ), )))); } } |
Screenshot if image NOT found :-
Screenshot on Image found :-
Also Read:
Hello,
Don’t Panic, Panic is paralyzing. Here I am with the solutions that will solve If your network image is not showing in your flutter project in android studio.
Could Be This
- First please check your internet connection. it’s okay and working.
- Second Check The Code Again, No Typo Or Wrong Code.
Sample Project / Sample Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import ‘package:flutter/material.dart’; void main() => runApp( MaterialApp( home: Scaffold( appBar: AppBar( backgroundColor: Colors.blueGrey[900], title: Center( child: Text(‘i am rich’), ), titleSpacing: 0.0, ), backgroundColor: Colors.amber, body: Image( image: NetworkImage(‘http://amialif.com/images/woman.jpg’), ), ), ), ); |
Check and Match your code with above code snippet and If it’s still not loading then please add this two lines in your android/app/src/main/AndroidManifest.xml
Solution Of Your Problem:
You have to place these two lines of code after the application scope.
<uses—permission android:name=«android.permission.INTERNET» /> <uses—permission android:name=«android.permission.ACCESS_NETWORK_STATE» /> |
Note: Make Sure after you added the lines please give a restart to your android studio and rerun your project I hope it will solve your problem and you will be able to see your desired output.
Final Output:
Environment Of Development:
- Android Studio 3.5.3
- AVD: nexus 6 API 28 Android 9.0
Congratulations. You have solved your problem. If you are looking more Flutter Related Articles and Hack please Visite FLUTTER page. We have listed down all of our articles and many more are coming.
I hope you like this article. See you in the next articles when you will revisit me again. Bye…
Java # JSF # Spring # Hibernate # PHP # Python # Dart # Flutter # MySql # Oracle #JavaScript # jQuery # BootStrap 4 # CSS3 # HTML5
I love to explore new technologies. If you like my tutorials please share your thoughts about my work.
Check out my YouTube Channel For Video Tutorials.
To Hire Me Please Contact Me Through Social Media or https:www.amialif.com
If you want to help others by doing donation please Donate To These Charities.
You also can connect with me via social media. Thanks
I have implemented this StatefulWidget for the same case, hope this helps!!!
class NetworkImageHandlerViewer extends StatefulWidget {
final String imageURL;
bool errorFoundInImageLoad = false;
NetworkImageHandlerViewer({
Key key,
@required this.imageURL,
}) : super(key: key);
@override
_NetworkImageHandlerViewerState createState() =>
_NetworkImageHandlerViewerState();
}
class _NetworkImageHandlerViewerState extends State<NetworkImageHandlerViewer> {
@override
Widget build(BuildContext context) {
return Column(
children: [
Container(
height: 200,
// height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
// color: Colors.black,
child: (widget.errorFoundInImageLoad)
? Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Unable To Fetch Image",
),
IconButton(
iconSize: 40,
onPressed: () {
setState(() {
if (mounted) {
print("reloading image again");
setState(() {
widget.errorFoundInImageLoad = false;
});
}
});
},
icon: Icon(Icons.refresh),
),
Text(
"Tap Refresh Icon To Reload!!!",
),
],
)
: Image.network(
// widget.question.fileInfo[0].remoteURL,
widget.imageURL,
//
loadingBuilder: (context, child, loadingProgress) =>
(loadingProgress == null)
? child
: Center(
child: CircularProgressIndicator(),
),
errorBuilder: (context, error, stackTrace) {
Future.delayed(
Duration(milliseconds: 0),
() {
if (mounted) {
setState(() {
widget.errorFoundInImageLoad = true;
});
}
},
);
return SizedBox.shrink();
},
),
),
SizedBox(height: 25),
],
);
}
}