saveAndLaunchFile static method
To save the Excel file in the device
Implementation
/*static Future<void> saveAndLaunchFileOld(
List<int> bytes, String fileName) async {
String? path;
if (Platform.isAndroid) {
// final Directory? directory = await getExternalStorageDirectory();
final Directory? directory = await getApplicationDocumentsDirectory();
if (directory != null) {
path = directory.path;
}
} else if (Platform.isIOS || Platform.isLinux || Platform.isWindows) {
final Directory directory = await getApplicationSupportDirectory();
path = directory.path;
} else {
path = await PathProviderPlatform.instance.getApplicationSupportPath();
}
final File file =
File(Platform.isWindows ? '$path\\$fileName' : '$path/$fileName');
await file.writeAsBytes(bytes, flush: true);
if (Platform.isAndroid || Platform.isIOS) {
final Map<String, String> argument = <String, String>{
'file_path': '$path/$fileName'
};
try {
//ignore: unused_local_variable
final Future<Map<String, String>?> result =
_platformCall.invokeMethod('viewExcel', argument);
} catch (e) {
throw Exception(e);
}
} else if (Platform.isWindows) {
await Process.run('start', <String>['$path\\$fileName'],
runInShell: true);
} else if (Platform.isMacOS) {
await Process.run('open', <String>['$path/$fileName'], runInShell: true);
} else if (Platform.isLinux) {
await Process.run('xdg-open', <String>['$path/$fileName'],
runInShell: true);
}
}*/
static Future<void> saveAndLaunchFile(
List<int> bytes, String fileName) async {
late String directoryPath;
if (Platform.isAndroid) {
const String downloadPath = '/storage/emulated/0/Download';
// Ensure folder exists
final Directory downloadDir = Directory(downloadPath);
if (!downloadDir.existsSync()) {
downloadDir.createSync(recursive: true);
}
directoryPath = downloadPath; // <-- ONLY DIRECTORY
}
else if (Platform.isIOS || Platform.isLinux || Platform.isWindows) {
final Directory dir = await getApplicationSupportDirectory();
directoryPath = dir.path;
}
else {
final Directory dir = await getApplicationDocumentsDirectory();
directoryPath = dir.path;
}
// Now create FULL FILE PATH only once:
final String fullPath = Platform.isWindows
? "$directoryPath\\$fileName"
: "$directoryPath/$fileName";
final File file = File(fullPath);
await file.writeAsBytes(bytes, flush: true);
print("Saved File Path: $fullPath");
AppUtils.showSnackBar("File downloaded successfully: $fileName");
// Open file
await OpenFilex.open(fullPath);
}