我想在我的程序中使用flutter的Material设计图标,为此,我需要使用Icon小部件。我有一张网络图像(NetworkImage 小部件),如果 URL 为空,我想显示 Material design 图标。
Container(
width: 48.0,
height: 48.0,
decoration: BoxDecoration(
image: DecorationImage(
image: imgLink.isEmpty
? Icon(Icons.person_outline)
: NetworkImage(
imgLink,
),
),
borderRadius: BorderRadius.circular(10.0)),
),
它显示错误,因为图标不是 ImageProvider 的子类型。现在我如何将 Icon 转换为 ImageProvider 或任何其他方式。
解决方案是创建您自己的提供程序来转换图标:
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class IconImageProvider extends ImageProvider<IconImageProvider> {
final IconData icon;
final double scale;
final int size;
final Color color;
IconImageProvider(this.icon, {this.scale = 1.0, this.size = 48, this.color = Colors.white});
@override
Future<IconImageProvider> obtainKey(ImageConfiguration configuration) => SynchronousFuture<IconImageProvider>(this);
@override
ImageStreamCompleter load(IconImageProvider key, DecoderCallback decode) => OneFrameImageStreamCompleter(_loadAsync(key));
Future<ImageInfo> _loadAsync(IconImageProvider key) async {
assert(key == this);
final recorder = ui.PictureRecorder();
final canvas = Canvas(recorder);
canvas.scale(scale, scale);
final textPainter = TextPainter(textDirection: TextDirection.ltr);
textPainter.text = TextSpan(
text: String.fromCharCode(icon.codePoint),
style: TextStyle(
fontSize: size.toDouble(),
fontFamily: icon.fontFamily,
color: color,
),
);
textPainter.layout();
textPainter.paint(canvas, Offset.zero);
final image = await recorder.endRecording().toImage(size, size);
return ImageInfo(image: image, scale: key.scale);
}
@override
bool operator ==(dynamic other) {
if (other.runtimeType != runtimeType) return false;
final IconImageProvider typedOther = other;
return icon == typedOther.icon && scale == typedOther.scale && size == typedOther.size && color == typedOther.color;
}
@override
int get hashCode => hashValues(icon.hashCode, scale, size, color);
@override
String toString() => '$runtimeType(${describeIdentity(icon)}, scale: $scale, size: $size, color: $color)';
}
这是标准的
ImageProvider
,所有库存的看起来都像这样。实际的转换在_loadAsync()
内部。相当简单,只是一个普通的 Canvas
操作,将图标绘制为文本(实际上,它是文本)。
BoxDecoration
的
Container
中的Image仅支持ImageProvider类,该类具有 以下实施者
AssetBundleImageProvider
,FileImage
,MemoryImage
,NetworkImage
,ResizeImage
,ScrollAwareImageProvider
所以它不支持图标小部件,因为图标小部件有自己的IconData类,这就是为什么flutter会给你错误, “图标不是图像提供者”。