flutter - How to convert icon widget to ImageProvider
问题描述
I want to use the Material design icons of flutter in my program, for that, I need to use the Icon widget. I have one network image (NetworkImage widget) and I want to display the Material design icon if there is an empty URL.
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)),
),
it shows error as icons is not a subtype of ImageProvider. Now how I can convert Icon to ImageProvider or any other way.
解决方案
解决方案是创建您自己的转换图标的提供程序:
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.rtl);
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
将图标绘制为文本的正常操作(实际上是文本)。
推荐阅读
- python - 如何获取Dataframe中最大值和最小值的上一个和下一个值
- php - 如何在php网页上显示两个表格数据
- c - inet_ntop() 未在此范围内清除
- python - Scikit-Learn + Scipy.optimize 高斯过程回归中的外部优化器
- xml - 从结构生成特定格式的 XML
- javascript - 什么时候可以考虑断开 RTCPeerConnection?
- azure - 如何为 MS Azure Speech to Text 服务启用字级置信度
- javascript - Jest 测试在本地通过,但在 azure devops 中失败
- java - Maven:如何将现有的 Maven 项目拆分为不同的项目?
- angularjs - 多次调用模板与 ng-repeat 内的调用