Flutter : Display Local Image when Network Image not found or error fetching it?
3,871
Solution 1
You can use FadeInImage
widget for your use case..
Here's a sample for you..
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final title = 'Fade in images';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: FadeInImage.assetNetwork(
placeholder: 'assets/loading.gif',
image: 'https://picsum.photos/250?image=9',
),
),
),
);
}
}
You can get more information from official website.
Solution 2
Make Sure image exist in the asset folder in the path. for Eg:
errorWidget: (context, url, error) => Image.asset('assets/images/image.jpg'),
And declare that path inside pubspec.yaml
file.
Eg:
assets:
- assets/images/image.png
Author by
mocha234
Updated on December 21, 2022Comments
-
mocha234 over 1 year
Center( child: CachedNetworkImage( imageUrl: "http:/ sosme link here", errorWidget: (context, url, error) => Icon(Icons.error), fadeInCurve: Curves.easeIn , fadeInDuration: Duration(milliseconds:1000), fadeOutCurve: Curves.easeOut, fadeOutDuration: Duration(milliseconds:500), imageBuilder: (context, imageProvider) => Container( height: 250.0, width: 250.0, decoration: BoxDecoration( border: Border.all( color: Colors.black, ), borderRadius: BorderRadius.all(Radius.circular(10)), color: Colors.white, image: DecorationImage( image: imageProvider, fit: BoxFit.cover, ), ), ), ), ),
My goal is to load image from URL that may and may not exist. In case of not existing URL, load asset image. Tried insert asset image here, but didnt't work. As I was thinking if there's error loading it, means no image found or something else. So I wanna display a local image instead.
Any Suggestion?
errorWidget: (context, url, error) => Icon(Icons.error),
Error, when i use asset image
-
mocha234 almost 4 yearsHello. I tried that. But assuming the URL is not available, it gave me an error(I edited the question by uploading a screenshot).
-
Jitesh Mohite almost 4 years@nelsonwong: in your code, I can't see Exception handling, even if you put the wrong URL my code should work as per CachedNetworkImage
-
mocha234 almost 4 yearsThanks to @srikanth7785 Solved by using Try/Catch block.
-
JCWasmx86 over 3 yearsAn explanation would improve this answer