如何从Flutter-web中的小部件创建图像?

问题描述

要在Google地图google_maps_flutter显示自定义窗口小部件,我使用了一个非常方便的功能,可以将任何Widget包括那些包含图像的图像)转换为Image,然后将其转换为{ {1}}我需要。它在iOS和Android上都很好用。

Uint8List

但是不幸的是,当我尝试在Web上使用此功能时,出现以下错误

不受支持的操作:Web不支持toImage

现在Flutter支持Future createImageFromWidget( Widget widget){ final RenderRepaintBoundary repaintBoundary = RenderRepaintBoundary(); final RenderView renderView = RenderView( child: RenderPositionedBox(alignment: Alignment.center,child: repaintBoundary),configuration: ViewConfiguration(size: const Size.square(300.0),devicePixelRatio: ui.window.devicePixelRatio),window: null,); final PipelineOwner pipelineOwner = PipelineOwner()..rootNode = renderView; renderView.prepareInitialFrame(); final BuildOwner buildOwner = BuildOwner(); final RenderObjectToWidgetElement<RenderBox> rootElement = RenderObjectToWidgetAdapter<RenderBox>( container: repaintBoundary,child: Directionality( textDirection: TextDirection.ltr,child: IntrinsicHeight(child: IntrinsicWidth(child: widget)),),).attachToRenderTree(buildOwner); buildOwner..buildScope(rootElement)..finalizeTree(); pipelineOwner..flushLayout()..flushCompositingBits()..flushPaint(); return repaintBoundary.toImage(pixelRatio: ui.window.devicePixelRatio) .then((image) => image.toByteData(format: ui.ImageByteFormat.png)) .then((byteData) => byteData.buffer.asUint8List()); } Image.toByteData #20750,但我不知道该如何在我的情况下使用。

实际上,问题是-如何重新制作此功能,使其也可以在Web上使用?

谢谢,我对任何想法都很高兴

解决方法

repaintBoundary.toImage功能取决于Scene.toImage,根据问题#42767的注释,尚未针对Web实现。
该问题目前也没有优先考虑。

, 如果您将 --dart-define=FLUTTER_WEB_USE_SKIA 放在 flutter build web 参数上,

toImage() 会起作用。

该方法无需此参数即可在本地运行。

我在看到 crop 包文档后找到了这个解决方案,它也使用了 toImage()

编辑

我在通过 iPhone 访问应用程序时发现了一些问题,从小部件生成图像的工作正常,但我在项目中的一些动画停止工作。

我发现了这个 question,我将仅使用参数 --dart-define=FLUTTER_WEB_AUTO_DETECT=true 进行一些测试,以查看是否在桌面、Android 和 iOS 上使用 Flutter web 正常工作。

编辑 2

在 MacO 上进行一些测试后,toImage() 方法也能正常工作。