ByteArray not written to disk on time

Viewed 35

Hi I am trying to build a sharing functionality in flutter which takes a screenshot on my app and then shares it.

share(BuildContext context) async {
    var boundary = _globalKey.currentContext!.findRenderObject();
    if (boundary is RenderRepaintBoundary) {
      if (boundary.debugNeedsPaint) {
        Timer(Duration(seconds: 1), () => share(context));
        return null;
      }
      var image = await boundary.toImage(pixelRatio: 1.0);
      var bytes = await image.toByteData(format: ImageByteFormat.png);
      var imgByteArray = bytes!.buffer.asUint8List();
      var tmpDir = await getTemporaryDirectory();
      var tmpFilePath = "${tmpDir.path}/screenshotofdoom.png";
      var tmpImageFile = File(tmpFilePath);
      // this line doesn't behave as expected
      await tmpImageFile.writeAsBytes(imgByteArray, flush: true);
      final RenderBox box = context.findRenderObject() as RenderBox;
      // This is a hack and should not be necesary
      Timer(Duration(seconds: 1), () {
        Share.shareFiles([tmpFilePath],
            mimeTypes: ["image/png"], subject: "Aqui esta tu codigo de control de accesos", sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size);
      });
    }
  }

it currently works but it feels hacky, if I remove the timer at the end of the function, it shares a black screen, with the timer it gets shared sometimes the greater the timer duration the more probable it is ready. is there any way to ensure it gets written that does not rely on waiting an arbitrary amount of time?

1 Answers

You can try checking if the length of the file on disk is non-zero in a loop with a short delay to avoid wasted cycles:

await tmpImageFile.writeAsBytes(imgByteArray, flush: true);

// Check that the file contents have been written to disk.
while (await tmpImageFile.length() == 0) {
  await Future.delayed(const Duration(milliseconds: 10));
}

Share.shareFiles(...);

However, I'm surprised that the file isn't being flushed to disk. What platform are you running on? It might be worth filing an issue on the Dart SDK issue tracker so we can investigate why this isn't behaving as you'd expect.

Related