【问题标题】:Flutter save widget directly into an imageFlutter 将小部件直接保存到图像中
【发布时间】:2020-11-18 02:39:33
【问题描述】:

我有一个想要保存到 png 图像中的自定义小部件。 我面临的问题是,当前的实现是我需要在屏幕上显示小部件。 我想要的是将小部件直接保存到图像中而不显示它。

作为一种解决方法,我会在图像呈现在屏幕上的第一时间保存图像,然后迅速将其关闭。

这就是我现在保存小部件的方式:


class SomeWidget extends StatefulWidget {
  const SomeWidget({
    Key key,
  }) : super(key: key);

  @override
  _ShareCocktailMockState createState() => _ShareCocktailMockState();
}

class _SomeWidgetState extends State<SomeWidget>
    with AfterLayoutMixin<SomeWidget> {
  GlobalKey globalKey = GlobalKey();

  Future<void> _capturePng() async {
    RenderRepaintBoundary boundary =
        globalKey.currentContext.findRenderObject();
    try {
      if (boundary.debugNeedsPaint) {
        print("Waiting for boundary to be painted.");
        await Future.delayed(const Duration(milliseconds: 5));
        return _capturePng();
      }
    } catch (_) {}
    try {
      ui.Image image = await boundary.toImage();
      ByteData byteData =
          await image.toByteData(format: ui.ImageByteFormat.png);
      Uint8List pngBytes = byteData.buffer.asUint8List();

      // SHARING IMAGE TO SOCIAL MEDIA
      // CODE

      // widget is presented with a dialog so I just pop it
      Navigator.of(context).pop();
    } catch (_) {
      await Future.delayed(const Duration(milliseconds: 5));
      return _capturePng();
    }
  }

  @override
  void afterFirstLayout(BuildContext context) {
    _capturePng();
  }

  @override
  Widget build(BuildContext context) {
    return RepaintBoundary(
      key: globalKey,
      child: SuperFancyWidget(),
    );
  }
}

afterFirstLayout 来自https://pub.dev/packages/after_layout

【问题讨论】:

    标签: flutter dart mobile


    【解决方案1】:

    好的,如果你想将你的小部件保存为 png 图片,你可以使用screenshot 包。 像这样包装小部件:

    Screenshot(
        controller: screenshotController,
        child: Text("This text will be captured as image"),
    )
    

    请阅读自述文件部分了解包中的详细信息。

    【讨论】:

    • 你提到的包正是我在实现中设法做到的。我正在寻找一种解决方案来在图像中保存屏幕外小部件。但据我所知,目前这是不可能的。
    猜你喜欢
    • 1970-01-01
    • 2020-09-14
    • 2017-12-13
    • 2020-01-18
    • 2013-11-30
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    相关资源
    最近更新 更多