如何在Flutter中构建自定义图像提供程序?

时间:2020-09-18 09:11:26

标签: flutter

我想为自己的图像类编写图像提供程序。让我们以下面的小部件为图像类的示例。只要需要图像实例,就可以使用此窗口小部件。现在,我正在使用需要图像提供程序作为参数的小部件。如何构建自定义图片提供程序? (我知道现有的dart程序包,但这里的问题是如何编写自己的图像提供程序)

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();
  }
}

2 个答案:

答案 0 :(得分:1)

我按照FileImage编写自己的ImageProvider,我不精通这个所以小心它可能有问题(例如我没有用gif测试它),你也可以阅读{{ 1}},它比 FileImage 代码少,易于阅读。

NetworkImage

并使用它:

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")';
}

答案 1 :(得分:0)

对于那些正在寻找在 Flutter Web 图像中添加标题的解决方案的人, 我根据@nillouise 的回答建立了我的课程。令人惊讶的是,它有效!


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")';
}