saveFileNative method

Future<String?> saveFileNative(
  1. Uint8List bytes,
  2. String defaultName,
  3. String extension
)

Implementation

Future<String?> saveFileNative(Uint8List bytes, String defaultName, String extension) async {
  if (kIsWeb) {
    // Web: use HTML5 download
    downloadFileWeb(bytes, '$defaultName.$extension');
    return null; // Web doesn't return a path
  }

  if (Platform.isAndroid || Platform.isIOS) {
    try {
      final result = await FilePicker.platform.saveFile(
        dialogTitle: 'Save file',
        fileName: defaultName,
        type: FileType.custom,
        allowedExtensions: [extension],
        bytes: bytes, // Required on Android/iOS
      );
      if (result != null) {
        return result;
      }
    } catch (e) {
      // Ignore errors, return null
    }
    return null;
  }

  if (Platform.isLinux) {
    // Try zenity
    try {
      final result = await Process.run('zenity', [
        '--file-selection',
        '--save',
        '--confirm-overwrite',
        '--filename=$defaultName',
        '--file-filter=*.$extension',
        '--title=Save file',
      ]);
      if (result.exitCode == 0) {
        var path = (result.stdout as String).trim();
        if (path.isNotEmpty) {
          if (!path.endsWith('.$extension')) path += '.$extension';
          final file = File(path);
          await file.writeAsBytes(bytes);
          return path;
        }
      }
    } catch (_) {}

    // Try kdialog
    try {
      final result = await Process.run('kdialog', [
        '--getsavefilename',
        defaultName,
        '*.$extension',
      ]);
      if (result.exitCode == 0) {
        var path = (result.stdout as String).trim();
        if (path.isNotEmpty) {
          if (!path.endsWith('.$extension')) path += '.$extension';
          final file = File(path);
          await file.writeAsBytes(bytes);
          return path;
        }
      }
    } catch (_) {}
  } else if (Platform.isMacOS || Platform.isWindows) {
    try {
      final location = await getSaveLocation(suggestedName: defaultName);
      if (location != null) {
        var path = location.path;
        if (!path.endsWith('.$extension')) path += '.$extension';
        final file = File(path);
        await file.writeAsBytes(bytes);
        return path;
      }
    } catch (_) {}
  }

  return null;
}