'How to build a custom image provider in flutter?

I want to write an image provider for my own image class. Let's take the widget below as a sample for an image class. This widget can be used whenever a image instance is needed. Now I'm using a widget which needs an image provider as parameter. How can I build a cusom image provider? (I know about the existing dart packages but the question here is how to write my own image provider)

class _AppImageState extends State<AppImage> {
  Uint8List imageData;

  Future download({iterate = 0}) async {
    if (iterate >= 5) {
      Log.w("too many iterations for ${widget.url}");
      return;
    }

    var response;
    try {
      var request = await HttpClient().getUrl(Uri.parse(widget.url));
      response = await request.close();
    } catch (e) {
      Log.e(e);
      return Timer(Duration(seconds: iterate + 1), () => download(iterate: iterate + 1));
    }

    try {
      if (response != null && response.statusCode == 200) {
        Uint8List bytes = await consolidateHttpClientResponseBytes(response);
        setState(() {
          imageData = bytes;
        });
      } else {
        return Timer(Duration(seconds: iterate + 1), () => download(iterate: iterate + 1));
      }
    } catch (e) {
      Log.e(e);
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    download();
  }

  @override
  Widget build(BuildContext context) {
    return imageData != null ? Image.memory(imageData) : widget.placeholder ?? Container();
  }
}


Solution 1:[1]

I follow the FileImage and write my own ImageProvider, I don't master at this so becareful it may have problem(for example I don't test it with gif), you also can read the FileImage, it is less code than the NetworkImage and easy to read.

class CacheImageProvider extends ImageProvider<CacheImageProvider> {
  final String fileId;//the cache id use to get cache

  CacheImageProvider(this.fileId);

  @override
  ImageStreamCompleter load(CacheImageProvider key, DecoderCallback decode) {
    return MultiFrameImageStreamCompleter(
      codec: _loadAsync(decode),
      scale: 1.0,
      debugLabel: fileId,
      informationCollector: () sync* {
        yield ErrorDescription('Path: $fileId');
      },
    );
  }

  Future<Codec> _loadAsync(DecoderCallback decode) async {
    // the DefaultCacheManager() encapsulation, it get cache from local storage.
    final Uint8List bytes = await (await CacheThumbnail.getThumbnail(fileId)).readAsBytes();

    if (bytes.lengthInBytes == 0) {
      // The file may become available later.
      PaintingBinding.instance?.imageCache?.evict(this);
      throw StateError('$fileId is empty and cannot be loaded as an image.');
    }

    return await decode(bytes);
  }

  @override
  Future<CacheImageProvider> obtainKey(ImageConfiguration configuration) {
    return SynchronousFuture<CacheImageProvider>(this);
  }
  
  //the custom == and hashCode must be write, because the ImageProvider memory cache use it to identify the same image.
  @override
  bool operator ==(Object other) {
    if (other.runtimeType != runtimeType) return false;
    bool res = other is CacheImageProvider && other.fileId == fileId;
    return res;
  }

  @override
  int get hashCode => fileId.hashCode;

  @override
  String toString() => '${objectRuntimeType(this, 'CacheImageProvider')}("$fileId")';
}

and use it:

Image(image: CacheImageProvider(_data[index].fileId))

Solution 2:[2]

Here is a solution I found. I hope this will help you

import 'dart:typed_data';
import 'dart:ui';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

class CacheImageProvider extends ImageProvider<CacheImageProvider> {
  final String tag; //the cache id use to get cache
  final Uint8List img; //the bytes of image to cache

  CacheImageProvider(this.tag, this.img);

  @override
  ImageStreamCompleter load(CacheImageProvider key, DecoderCallback decode) {
    return MultiFrameImageStreamCompleter(
      codec: _loadAsync(decode),
      scale: 1.0,
      debugLabel: tag,
      informationCollector: () sync* {
        yield ErrorDescription('Tag: $tag');
      },
    );
  }

  Future<Codec> _loadAsync(DecoderCallback decode) async {
    // the DefaultCacheManager() encapsulation, it get cache from local 
    storage.
    final Uint8List bytes = img;

    if (bytes.lengthInBytes == 0) {
      // The file may become available later.
      PaintingBinding.instance?.imageCache?.evict(this);
      throw StateError('$tag is empty and cannot be loaded as an image.');
    }

    return await decode(bytes);
  }

  @override
  Future<CacheImageProvider> obtainKey(ImageConfiguration configuration) {
    return SynchronousFuture<CacheImageProvider>(this);
  }

  @override
  bool operator ==(Object other) {
    if (other.runtimeType != runtimeType) return false;
    bool res = other is CacheImageProvider && other.tag == tag;
    return res;
  }

  @override
  int get hashCode => tag.hashCode;

  @override
  String toString() =>
      '${objectRuntimeType(this, 'CacheImageProvider')}("$tag")';
}

Solution 3:[3]

For those searching for a solution to adding headers in Flutter Web images, I based my class from the answer of @nillouise. Surprisingly, it works!


String TOKEN;
String URLBASE;

class AuthImageProvider extends ImageProvider<AuthImageProvider> {
  final String relativeUrl;
  Future<http.Response> resp;

  AuthImageProvider(this.relativeUrl) {
    Map<String, String> h = {"Authorization": "bearer $TOKEN"};
    resp = http.client.get(URLBASE + relativeUrl, headers: h);
  }

  @override
  ImageStreamCompleter load(AuthImageProvider key, decode) {
    return MultiFrameImageStreamCompleter(
        codec: _loadAsync(decode), scale: 1.0);
    throw UnimplementedError();
  }

  Future<Codec> _loadAsync(DecoderCallback decode) async {
    // the DefaultCacheManager() encapsulation, it get cache from local storage.
    final bytes = (await resp).bodyBytes;
    if (bytes.lengthInBytes == 0) {
      // The file may become available later.
      PaintingBinding.instance?.imageCache?.evict(this);
      throw StateError(
          '$relativeUrl is empty and cannot be loaded as an image.');
    }

    return await decode(bytes);
  }

  @override
  Future<AuthImageProvider> obtainKey(ImageConfiguration configuration) {
    return SynchronousFuture<AuthImageProvider>(this);
  }

  @override
  bool operator ==(Object other) {
    if (other.runtimeType != runtimeType) return false;
    bool res = other is AuthImageProvider && other.relativeUrl == relativeUrl;
    return res;
  }

  @override
  int get hashCode => relativeUrl.hashCode;

  @override
  String toString() =>
      '${objectRuntimeType(this, 'CacheImageProvider')}("$relativeUrl")';
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nillouise
Solution 2 Abdalla Bersanukaev
Solution 3 Juancki