Flutter - how to catch FileSystemExceptions?

258 Views Asked by At

My flutter app saves screenshots to disk (on Flutter desktop Mac and Windows). If writing fails due to whatever reason catch and error handling does not work. Statements after "catch" will never be executed despite debug output shows

[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: FileSystemException: Cannot open file ...]

What am I missing here?

actual code snippet:

final dFile = File('$dPath(AS-Logo) $logoText.png');
screenshotController
    .captureFromWidget(makeLogoShow(completeImageSize, logoText))
    .then((capturedImage) {
  try {
    dFile.writeAsBytes(capturedImage);
  } on FileSystemException catch (e) {
    print("Error: $e");
    return false;
  }
});
1

There are 1 best solutions below

3
On

So the way I solved this was to write a different function to convert the widget to an Image file.

File _processWidgetImage() {
  String yourFilePath = 'your/file/path.png';
  Future<Uint8List> image = screenshotController
  .captureFromWidget(makeLogoShow(completeImageSize, logoText));
  Future<File> f = _widgetToImageFile(image, yourFilePath);
  return await f;
}

Future<File> _widgetToImageFile(Future<Uint8List> capturedImage, String path) async {
  Uint8List cp = await capturedImage;
  final dFile = await File(path).writeAsBytes(cp);
  return dFile;
}

You should post your makeLogoShow method. There may be something in there that's not working right also. That method needs to return a viewable widget.