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?