Files
FlClash/lib/common/picker.dart
T

69 lines
2.0 KiB
Dart
Raw Normal View History

2024-08-23 18:33:40 +08:00
import 'dart:io';
2024-08-04 08:21:14 +08:00
import 'dart:typed_data';
2024-04-30 23:38:49 +08:00
import 'package:file_picker/file_picker.dart';
2024-05-11 17:02:34 +08:00
import 'package:fl_clash/common/common.dart';
import 'package:image_picker/image_picker.dart';
2025-02-03 23:32:00 +08:00
import 'package:mobile_scanner/mobile_scanner.dart';
2024-04-30 23:38:49 +08:00
2024-05-11 17:02:34 +08:00
class Picker {
2025-12-16 11:23:09 +08:00
Future<PlatformFile?> pickerFile({bool withData = true}) async {
2024-07-07 10:02:10 +08:00
final filePickerResult = await FilePicker.platform.pickFiles(
2025-12-16 11:23:09 +08:00
withData: withData,
2024-07-07 10:02:10 +08:00
allowMultiple: false,
2025-02-03 23:32:00 +08:00
initialDirectory: await appPath.downloadDirPath,
2024-07-07 10:02:10 +08:00
);
return filePickerResult?.files.first;
}
2024-08-23 18:33:40 +08:00
Future<String?> saveFile(String fileName, Uint8List bytes) async {
2024-08-04 08:21:14 +08:00
final path = await FilePicker.platform.saveFile(
fileName: fileName,
2025-02-03 23:32:00 +08:00
initialDirectory: await appPath.downloadDirPath,
2025-12-16 11:23:09 +08:00
bytes: bytes,
2024-07-07 10:02:10 +08:00
);
2025-06-07 01:48:34 +08:00
if (!system.isAndroid && path != null) {
2025-12-16 11:23:09 +08:00
final file = File(path);
await file.safeWriteAsBytes(bytes);
2024-08-23 18:33:40 +08:00
}
2024-08-04 08:21:14 +08:00
return path;
2024-04-30 23:38:49 +08:00
}
2024-05-11 17:02:34 +08:00
2025-12-16 11:23:09 +08:00
Future<String?> saveFileWithPath(String fileName, String localPath) async {
final localFile = File(localPath);
if (!await localFile.exists()) {
await localFile.create(recursive: true);
}
final bytes = Platform.isAndroid ? await localFile.readAsBytes() : null;
final path = await FilePicker.platform.saveFile(
fileName: fileName,
initialDirectory: await appPath.downloadDirPath,
bytes: bytes,
);
if (path != null && bytes == null) {
await localFile.copy(path);
}
await localFile.safeDelete();
return path;
}
2024-06-03 18:02:05 +08:00
Future<String?> pickerConfigQRCode() async {
2024-05-11 17:02:34 +08:00
final xFile = await ImagePicker().pickImage(source: ImageSource.gallery);
2025-02-03 23:32:00 +08:00
if (xFile == null) {
return null;
}
final controller = MobileScannerController();
2025-07-31 17:09:18 +08:00
final capture = await controller.analyzeImage(
xFile.path,
formats: [BarcodeFormat.qrCode],
);
2025-02-03 23:32:00 +08:00
final result = capture?.barcodes.first.rawValue;
2024-05-11 17:02:34 +08:00
if (result == null || !result.isUrl) {
2024-06-03 18:02:05 +08:00
throw appLocalizations.pleaseUploadValidQrcode;
2024-05-11 17:02:34 +08:00
}
2024-06-03 18:02:05 +08:00
return result;
2024-05-11 17:02:34 +08:00
}
2024-04-30 23:38:49 +08:00
}
2024-05-11 17:02:34 +08:00
final picker = Picker();