Removing image from cache when using Image.network - flutter

Im using Image.Network to display a image based on a URL :
ClipOval(
child: Image.network(
'http://myurl${userId}.png',
width: 100,
height: 100,
fit: BoxFit.cover,
key: profileImageKey,
),
),
I'm trying get the user to upload a new profile image, however, i'm retaining the same filename (userid + .png). Once the user has uploaded the image the above is display is not displaying the new image.
I've tried rebuilding the widget using :
setState(() {
//generateKey();
profileImageKey = ValueKey(new Random().nextInt(100));
userId = userId;
});
I've also tried removing the url from the cache using :
PaintingBinding.instance.imageCache.evict('http://myurl${userId}.png');
However, none of these methods work. Is there a way to update the Image.Network to download and use the new image that was uploaded ?
Thanks

Based on #pskink's comment https://stackoverflow.com/a/60916852/2252830
The solution to this question was to use the evict method on Image. So I refactored my code to below :
Image profileImage;
...
profileImage = Image.network(
'http://myurl${userId}.png',
width: 100,
height: 100,
fit: BoxFit.cover,
key: profileImageKey,
);
...
ClipOval(
child: profileImage,
),
...
profileImage.image.evict();
setState(() {
//generateKey();
profileImageKey = ValueKey(new Random().nextInt(100));
userId = userId;
});

Related

Unable to execute inner statements of a for loop in Dart

I am trying to display an image in my weather app based on the current weather condition.
I have a jsonConditionsDay variable which stores JSON data fetched from https://www.weatherapi.com/docs/conditions.json.
I have a List<String> conditionsDayImgUrls = []; //network image urls contained in this which stores image urls.
Current weather data is fetched using dio from https://www.weatherapi.com/api-explorer.aspx#forecast and stored in a variable jsonData.
Now when I'm calling the following function String getCurrentConditionsBgImgForDay(String str) I am not getting the desired image from the conditionsDayImgUrls list, instead I'm only getting the first image of the list.
Code for getCurrentConditionsBgImgForDay in global_variables.dart:
String getCurrentConditionsBgImgForDay(String str) {
int i;
for (i = 0; i < jsonConditions.length; i++) {
if (str == jsonConditions[i]["day"]) {
return conditionsDayImgUrls[i];
}
}
//print(i);
return conditionsDayImgUrls[0];
}
The following code in current_weather_screen.dart tries to display the desired weather image based on current weather condition:
Container(
width: screenWidth,
height: screenHeight,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(
getCurrentConditionsBgImgForDay(
jsonData["current"]
["condition"]["text"])),
fit: BoxFit.fill,
),
),
),
What is wrong in my code that is preventing it from displaying the correct weather image and how to solve it?

Exception Flutter from fetch network Image without connection internet

after turning off the internet i gets this error: "Remove network images from cache on any exception during loading"
my app fetch pictures from api. how can i fix this bug how i prevent that?
return Column(children: [
GestureDetector(
child: Image.network(thumbnailUrl))])
You can use the Cached Network Image Plugin if you are developing for android and ios. In Web, the plugin is not working as expected.
Use the following as a widget for your application.
import 'package:cached_network_image/cached_network_image.dart';
Widget commonCacheImageWidget(String? url, {double? width, BoxFit? fit, double? height}) {
if (url!.startsWith('http')) {
return CachedNetworkImage(
placeholder: (context, url) => Image.asset('assets/path....', fit: BoxFit.cover),
imageUrl: url,
height: height,
width: width,
fit: fit,
);
} else {
return Image.asset(url, height: height, width: width, fit: fit);
}
}
In Placeholder you can have any widget, here am using a local image that is stored as an asset.
Or You can check whether the internet connection is there or not before loading the image and change that to some other widget.

How can I show the firebase storage image in flutter web. I have the image URL. show the URL not image. but another side image link is done perfectly

already I have the image URL. but when I try to fetch into my browser. the container show the URL not image. but another side image link is done perfectly. Please response about it.
the debug console show this error:
Failed to decode image data.
Image source: http://localhost:5982/
'For upload and retrieve'
String imageUrl = '';
final String downloadUrl = Uri.parse(await snapshot.ref.getDownloadURL()).toString();
setState(() {
imageUrl = downloadUrl;
});
For display image
Stack(
alignment: Alignment.bottomRight,
children: [
Container(
child: Image.network(imageUrl),
),
IconButton(
onPressed: () => uploadToStorage(dataProvider),
icon:
Icon(Icons.camera_alt, color: Colors.black54))
],
),'
Error into debug console:
Failed to decode image data.
Image source: http://localhost:5982/
I think you are looking for Image.network(urlForMyImage).
Ref. docs

Flutter : fetch image from picture Directory

I'm working with saved image from Url with Gallery Saver. Everything it's oke , i can insert image from URL, but i don't know how to fetch image from picture Directory .
It's different about getApplicationDocumentsDirectory() or getExternalStorageDirectory() ?
I want to display the image that was just saved.
Any solution ?
Save image Code :
void _testSaveImage() async {
String path = "${Urls.BASE_API_IMAGE}/berita/${widget.gambarBerita}";
GallerySaver.saveImage(path).then((bool success) {
print('Success add image $path');
}).catchError((onError) {
print('Error add image $path');
});
}
Location Image saved
Then just return the path you have and use a Image.file() widget to display it, lets say you have a Column():
Column(children: <Widget>[
[...]
Text('Here is my image:'),
if (path.isNotEmpty && path != null)
SizedBox(
height: 200,
width: 200,
child: Image.file(File(path),
),
Text('Caption of the image'),
[...]
),
Docs for Image class here
Load local saved images using path and use it
var file = new File('path');
Image.file(file )

"Unable to load asset" with image picker

I'm using Image Picker package in my Flutter project
I choose image from gallery then preview it in Image.asset widget
The problem here is if image name "example_name.png" (without spaces) the image is visible on the screen, but if image name "example name.png" (with spaces) the image is invisible like this Screenshot.
Error: Unable to load asset: /storage/emulated/0/Download/images (9).jpeg
File _image;
Image.asset(
_image != null
? "${_image.path}"
: getImage("icon.png"),
fit: BoxFit.cover,
width: 120,
height: 120,
);
...
Future chooseFile() async {
await ImagePicker.pickImage(source: ImageSource.gallery).then((image) {
setState(() {
_image = image;
});
});
}
You are using the wrong Image constructor. Use Image.file instead of Image.asset. Image.asset load files packaged in the application (assets section of pubspec.yaml) and ImagePicker does not have access to them.
in the image_picker (version 0.6.7 + 22) I was able to recover the image with this condition
if (photo == null) {
return Image (
image: AssetImage ('assets / no-image.png'),
height: 300.0,
fit: BoxFit.cover,
);
} else {
return Image.file (
Photo,
height: 300.0,
fit: BoxFit.cover,
);
}
Using Image.file is a good option but you like to display it in an effective way use
Image.file(_image).image this will help you to convert Image file to image provider