user532445
user532445

Reputation: 763

Show Local Images and Server Images ( with Caching) in Flutter

I am trying to show the image in a Widget picked from Image-Gallery as well as from the Network loaded images.

CachedNetworkImage is working fine with Network-images but when I try to pass selected image from gallery it's not working.

CachedNetworkImage(
      imageUrl: url,
      placeholder: (context, url) => new CircularProgressIndicator(),
      errorWidget: (context, url, error) => new Icon(Icons.error),
    );

Please help me to show this.

Objective is to 1. Can load local images 2. Can load network images 3. Can show Cached images.

Thank you in advance.

Upvotes: 2

Views: 2713

Answers (1)

Omatt
Omatt

Reputation: 10453

You need to determine when you'd like to display local image and when to display image from network. If the network image needs to display the local copy once it has been downloaded, you can add a checker if that image file exist locally. Else, the image should be fetched from network/cache. You can use the imageId of the image URL to be the same identifier for the local image.

var imgUrlEndpoint = 'https://picsum.photos/250?image='
var imgId = '9';
var imgFile = File('path/to/file/$imgId.jpg');

// Check if image file exists
if(imgFile.exists()){
  // Load image from storage
  Image.file(imgFile);
} else {
  // Load image from network
  CachedNetworkImage(
    imageUrl: '$imgUrlEndpoint$imgId',
    placeholder: (context, url) => CircularProgressIndicator(),
  );
}

Upvotes: 2

Related Questions