flutterImageProvider function

Future<ImageProvider> flutterImageProvider(
  1. ImageProvider<Object> image, {
  2. ImageConfiguration? configuration,
  3. ImageErrorListener? onError,
})

Loads an image from a Flutter ImageProvider into an ImageProvider instance

Implementation

Future<ImageProvider> flutterImageProvider(
  rdr.ImageProvider image, {
  rdr.ImageConfiguration? configuration,
  rdr.ImageErrorListener? onError,
}) async {
  final completer = Completer<ImageProvider>();
  final stream = image.resolve(configuration ?? rdr.ImageConfiguration.empty);

  late rdr.ImageStreamListener listener;
  listener = rdr.ImageStreamListener(
    (rdr.ImageInfo image, bool sync) async {
      final bytes = await image.image.toByteData();

      final result = RawImage(
        bytes: bytes!.buffer.asUint8List(),
        width: image.image.width,
        height: image.image.height,
      );

      if (!completer.isCompleted) {
        completer.complete(result);
      }
      stream.removeListener(listener);
    },
    onError: (dynamic exception, StackTrace? stackTrace) {
      if (!completer.isCompleted) {
        completer.completeError('image failed to load');
      }
      if (onError != null) {
        onError(exception, stackTrace);
      } else {
        // https://groups.google.com/forum/#!topic/flutter-announce/hp1RNIgej38
        assert(false, 'image failed to load');
      }
    },
  );

  stream.addListener(listener);
  return completer.future;
}