pickBackupFile method

Future<BackupModel?> pickBackupFile({
  1. required BackupModel decode(
    1. String
    ),
})

Shows the platform's native file explorer in order to pick a specific backup file.

If the requested fileExtension is not supported on the platform, no file extension filter will be applied.

Implementation

Future<BackupModel?> pickBackupFile({
  /// The serialization logic.
  ///
  /// The logic will vary from Model class to Model class and must be
  /// provided on each read-request.
  required BackupModel Function(String) decode,
}) async {
  FilePickerResult? result;

  try {
    // Allow extension filtering
    result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: [fileExtension],
    );
  } catch (e) {
    // Use default
    result = await FilePicker.platform.pickFiles();
    print("File Extention '$fileExtension' not supported on this device.");
    print(e);
  }

  if (result != null) {
    PlatformFile pickedfile = result.files.first;

    if (pickedfile.path == null) {
      print("Unable to locate file");
      return null;
    }

    print("Picked file cached at: " + pickedfile.path!);

    try {
      // Point to the cached backup file location.
      final file = await _createLocalFile(pickedfile.path!);
      // Read the file
      final contents = await file.readAsString();
      print("Backup found on ${file.path}");
      return decode(contents);
    } catch (e) {
      print(_ErrorMessage);
      print(e.toString());
      return null;
    }
  } else {
    // User canceled the picker
    print("Selecting file aborted.");
  }
}