PickedFile - How to show image on web? - flutter

The user picks an image (resulting in PickedFile - a class that is supported on web), and I want to present that image on the screen (another screen).
For Android and iOS it's very simple:
Image.file(
File(widget.pickedFile.path),
fit: BoxFit.scaleDown,
)
(see also How to Save set image of PickedFile type to a image in Flutter?).
However, for Web, the class File isn't supported.
How do I present the user with an Image on Web?

Without trying it personally, I suspect that PickedFile is a list of bytes.
Image has another constructor Image.memory() so my first suggestion is:
Uint8List pickedFileBytes = await widget.pickedFile.readAsBytes();
Image.memory(pickedFileBytes, fit: BoxFit.scaleDown);

To display pickedFile (local storage images) on Flutter Web use:
Image.network(file.path)
Hope this works for you :-)

file_picker: file.path not work in web becuase path always null.
solution: use file.bytes instead.
so try this solution worked for me :
Image.memory(
controller.file!.bytes!,
fit: BoxFit.fill,
height: 270,
width: Get.width,
)

Related

How to convert local storage image path into network image url in flutter

I have a local storage image path like:
/Users/newuser/Library/Developer/CoreSimulator/Devices/D7515987-8FDF-47A7-A6E1-A210739CB2A5/data/Containers/Data/Application/DC529635-F924-40DF-B530-85710D23A8D0/Library/Application Support/localstorage_images/2022-05-04/12:50:41.png
I have display this image using
image: FileImage(
url),
fit: BoxFit.cover,
),
here var url contains the local storage image path /Users/newuser/Library/Developer/CoreSimulator/Devices/D7515987-8FDF-47A7-A6E1-A210739CB2A5/data/Containers/Data/Application/DC529635-F924-40DF-B530-85710D23A8D0/Library/Application Support/localstorage_images/2022-05-04/12:50:41.png in File data type
I want to pass this var url in like below:
image: NetworkImage(
url),
fit: BoxFit.cover,
),
my problem was how to convert FileImage type to NetworkImage type because my other images are NetworkImage type it is possible to convert FileImage into Network image in flutter
Thanks in advance.

Flutter remove image after upload using image_picker package

I have managed to upload an image using the image picker package as shown below:
final picker = ImagePicker();
Future selectPhoto() async {
final pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
_image = File(pickedFile.path);
});
}
The image has been displayed on the device where I have a remove button which I can use to remove the image and upload another before saving it.
child: Container(
height: height * 0.2,
width: width * 0.2,
child: Image.file(
_image,
fit: BoxFit.fill,
),
),
My question is how can I remove the image from cache as this piece is not working
onTap: () {
setState(() {
imageCache.clear();
print('removes $_image');
});
},
You have a misunderstanding of what the cache is compared to explicitly storing a file in memory with your code. Flutter may store images that you use in widgets in a cache so that they may load faster in the future. imageCache.clear(); does clear the cache and is likely doing it's work in your code. However, your method of checking if the image is still cached is flawed.
imageCache.clear(); only clears the cache, it does not delete the file that you're passing to the Image.file widget. This means that _image(the file variable you have stored in memory) will persist even over the cache clearing. To truly delete this image you could use the delete method or if you just want to stop showing the image, deference the file by setting the file reference to null:
_image = null;
Solved it by calling a method within the button which had set state method where the path was returned back to null
clearimage() {
setState(() {
_image = null;
});
}

"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

FadeInImage with unknown image at runtime

I have a FadeInImage in my app, with the image loaded in response to a user action. This means at runtime, I dont know the image, and just want the FadeInImage to not display anything.
If I pass in null for the image, or an empty string, I get a runtime error.
flutter: ══╡ EXCEPTION CAUGHT BY IMAGE RESOURCE SERVICE ╞════════════════════════════════════════════════════
flutter: The following ArgumentError was thrown resolving an image codec:
flutter: Invalid argument(s): No host specified in URI file:///
Here it the relevant Widget declaration:
Container(
height: 100,
child:FadeInImage.memoryNetwork(
placeholder: kTransparentImage,
image: _d2apiModel.emblemUrl,
fit: BoxFit.fitWidth,
),
(where _d2apiModel is a Provider which is updated based on user actions).
I know I could put a default image in the asset bundle, copy it out of the bundle to the doc storage, get the file URI for the image, and use that as the default but 1) that seems like overkill, 2) i run into some async issues.
It seems like I am missing something obvious, but I cant figure out the approach. Any suggestions would be appreciated.
You can show a regular Image with kTransparentImage while your provider hasn't been updated, and then show your FadeInImage when it updates:
Container(
height: 100,
child: hasProviderBeenUpdated
? Image.memory(
kTransparentImage,
fit: BoxFit.fitWidth,
)
: FadeInImage.memoryNetwork(
placeholder: kTransparentImage,
image: _d2apiModel.emblemUrl,
fit: BoxFit.fitWidth,
),
),

How to fix Listview scrolling jank when loading images from network

I am loading images using Image.network for each item in a list using the following code:
Image getEventImageWidget(AustinFeedsMeEvent event) {
return event.photoUrl.isNotEmpty ?
Image.network(
event.photoUrl,
width: 77.0,
height: 77.0,
) : Image.asset(
'assets/ic_logo.png',
width: 77.0,
height: 77.0,
);
}
When I scroll up and down, the list sometimes hangs when loading the images. Is there a way I can load the images on a background thread? What can I do to help fix scrolling performance?
NOTE: When I looked back at this, I found that the images that I was using were really large.
There are two was to speed up the rendering of your ListView of images.
The first is to set the cacheExtent property to a larger value in your ListView constructor. This property controls how much offscreen widgets are rendered, and will help by causing the rendering to start a bit sooner.
The second is to pre-cache your images using precacheImage. Flutter has an in-memory cache, so it is generally to necessary to cache everything to disk to get good read performance. Instead, you can ask Flutter to download these images ahead of time so that they are ready when the widget is built. For example, if you have a list of urls of your image, then in an initState method you could ask Flutter to cache all of them.
final List<String> imageUrls = [ /* ... */ ];
#override
void initState() {
for (String url in imageUrls) {
precacheImage(new NetworkImage(url), context);
}
super.initState();
}
Are you sure your images are not very heavy? Check the size of the images first.
Also you can use the package named: cache_network_image
It's very simple :
new Image(image: new CachedNetworkImageProvider(url))
UPDATE (Package was updated)
CachedNetworkImage(
imageUrl: "http://via.placeholder.com/350x150",
placeholder: (context, url) => new CircularProgressIndicator(),
errorWidget: (context, url, error) => new Icon(Icons.error),
),
you can also use:
FadeInImage.assetNetwork(
placeholder: 'assets/ic_logo.png',
image: event.photoUrl,
height: 77.0,
width: 77.0,
fit: BoxFit.cover,
fadeInDuration: new Duration(milliseconds: 100),
),
but yeah, per diegoveloper, you sure your images aren't huge? Listview has no problem rendering anything that's close to reasonable in size.
You can create a Stateful Widget that creates the ListView with placeholder images, then have it have an async method you call after build() that loads the images from network (one by one) and then changes the state of the previously mentioned widget to replace the placeholder with the correct image. As a bonus, you can create a cache that stores the images so they don't have to be downloaded each time the ListView enters scope (here you would have the async method look in the cache for the image and if it doesn't find it there, download it).
As a side note, this would obviously require giving each of the images in the ListView an index.