image_render.dart 6.01 KB
Newer Older
汪林玲's avatar
汪林玲 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_html/html_parser.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:html/dom.dart' as dom;

typedef ImageSourceMatcher = bool Function(
  Map<String, String> attributes,
  dom.Element element,
);

ImageSourceMatcher base64DataUriMatcher() => (attributes, element) =>
    _src(attributes) != null &&
    _src(attributes).startsWith("data:image") &&
    _src(attributes).contains("base64,");

ImageSourceMatcher networkSourceMatcher({
  List<String> schemas: const ["https", "http"],
  List<String> domains,
  String extension,
}) =>
    (attributes, element) {
      if (_src(attributes) == null) return false;
      try {
        final src = Uri.parse(_src(attributes));
        return schemas.contains(src.scheme) &&
            (domains == null || domains.contains(src.host)) &&
            (extension == null || src.path.endsWith(".$extension"));
      } catch (e) {
        return false;
      }
    };

ImageSourceMatcher assetUriMatcher() => (attributes, element) =>
    _src(attributes) != null && _src(attributes).startsWith("asset:");

typedef ImageRender = Widget Function(
  RenderContext context,
  Map<String, String> attributes,
  dom.Element element,
);

ImageRender base64ImageRender() => (context, attributes, element) {
      final decodedImage =
          base64.decode(_src(attributes).split("base64,")[1].trim());
      precacheImage(
        MemoryImage(decodedImage),
        context.buildContext,
        onError: (exception, StackTrace stackTrace) {
          context.parser.onImageError?.call(exception, stackTrace);
        },
      );
      return Image.memory(
        decodedImage,
        frameBuilder: (ctx, child, frame, _) {
          if (frame == null) {
            return Text(_alt(attributes) ?? "",
                style: context.style.generateTextStyle());
          }
          return child;
        },
      );
    };

ImageRender assetImageRender({
  double width,
  double height,
}) =>
    (context, attributes, element) {
      final assetPath = _src(attributes).replaceFirst('asset:', '');
      if (_src(attributes).endsWith(".svg")) {
        return SvgPicture.asset(assetPath);
      } else {
        return Image.asset(
          assetPath,
          width: width ?? _width(attributes),
          height: height ?? _height(attributes),
          frameBuilder: (ctx, child, frame, _) {
            if (frame == null) {
              return Text(_alt(attributes) ?? "",
                  style: context.style.generateTextStyle());
            }
            return child;
          },
        );
      }
    };

ImageRender networkImageRender({
  Map<String, String> headers,
  String Function(String) mapUrl,
  double width,
  double height,
  Widget Function(String) altWidget,
  Widget Function() loadingWidget,
}) =>
    (context, attributes, element) {
      final src = mapUrl?.call(_src(attributes)) ?? _src(attributes);
      precacheImage(
        NetworkImage(
          src,
          headers: headers,
        ),
        context.buildContext,
        onError: (exception, StackTrace stackTrace) {
          context.parser.onImageError?.call(exception, stackTrace);
        },
      );
      Completer<Size> completer = Completer();
      Image image =
          Image.network(src, frameBuilder: (ctx, child, frame, _) {
        if (frame == null) {
          if (!completer.isCompleted) {
            completer.completeError("error");
          }
          return child;
        } else {
          return child;
        }
      });

      image.image.resolve(ImageConfiguration()).addListener(
            ImageStreamListener((ImageInfo image, bool synchronousCall) {
              var myImage = image.image;
              Size size =
                  Size(myImage.width.toDouble(), myImage.height.toDouble());
              if (!completer.isCompleted) {
                completer.complete(size);
              }
            }, onError: (object, stacktrace) {
              if (!completer.isCompleted) {
                completer.completeError(object);
              }
            }),
          );
      return FutureBuilder<Size>(
        future: completer.future,
        builder: (BuildContext buildContext, AsyncSnapshot<Size> snapshot) {
          if (snapshot.hasData) {
            return Image.network(
              src,
              headers: headers,
              width: width ?? _width(attributes) ?? snapshot.data.width,
              height: height ?? _height(attributes),
              frameBuilder: (ctx, child, frame, _) {
                if (frame == null) {
                  return altWidget?.call(_alt(attributes)) ??
                      Text(_alt(attributes) ?? "",
                          style: context.style.generateTextStyle());
                }
                return child;
              },
            );
          } else if (snapshot.hasError) {
            return altWidget?.call(_alt(attributes)) ?? Text(_alt(attributes) ?? "",
                style: context.style.generateTextStyle());
          } else {
            return loadingWidget?.call() ?? const CircularProgressIndicator();
          }
        },
      );
    };

ImageRender svgNetworkImageRender() => (context, attributes, element) {
      return SvgPicture.network(attributes["src"]);
    };

final Map<ImageSourceMatcher, ImageRender> defaultImageRenders = {
  base64DataUriMatcher(): base64ImageRender(),
  assetUriMatcher(): assetImageRender(),
  networkSourceMatcher(extension: "svg"): svgNetworkImageRender(),
  networkSourceMatcher(): networkImageRender(),
};

String _src(Map<String, String> attributes) {
  return attributes["src"];
}

String _alt(Map<String, String> attributes) {
  return attributes["alt"];
}

double _height(Map<String, String> attributes) {
  final heightString = attributes["height"];
  return heightString == null ? heightString : double.tryParse(heightString);
}

double _width(Map<String, String> attributes) {
  final widthString = attributes["width"];
  return widthString == null ? widthString : double.tryParse(widthString);
}