You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
59 lines
1.8 KiB
59 lines
1.8 KiB
// file_utils.dart |
|
import 'dart:async'; |
|
import 'dart:io'; |
|
import 'package:flutter/material.dart'; |
|
import 'package:file_picker/file_picker.dart'; |
|
import 'package:win_text_editor/framework/controllers/logger.dart'; |
|
|
|
class FileUtils { |
|
static Future<String?> pickFile(BuildContext context) async { |
|
try { |
|
final result = await FilePicker.platform.pickFiles(type: FileType.any, allowMultiple: false); |
|
return result?.files.single.path; |
|
} catch (e) { |
|
Logger().error('选择文件失败: ${e.toString()}'); |
|
if (context.mounted) { |
|
ScaffoldMessenger.of( |
|
context, |
|
).showSnackBar(SnackBar(content: Text('选择文件失败: ${e.toString()}'))); |
|
} |
|
return null; |
|
} |
|
} |
|
|
|
static Future<String?> readFileContent( |
|
BuildContext context, |
|
String filePath, { |
|
Duration timeout = const Duration(seconds: 30), |
|
}) async { |
|
try { |
|
final content = await File(filePath).readAsString().timeout( |
|
timeout, |
|
onTimeout: () { |
|
throw TimeoutException('文件加载超时,可能文件过大'); |
|
}, |
|
); |
|
return content; |
|
} on FormatException { |
|
if (context.mounted) { |
|
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('这不是可读的文本文件'))); |
|
} |
|
return null; |
|
} on FileSystemException catch (e) { |
|
if (context.mounted) { |
|
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('文件访问错误: ${e.message}'))); |
|
} |
|
return null; |
|
} catch (e) { |
|
Logger().error('读取文件失败: ${e.toString()}'); |
|
if (context.mounted) { |
|
ScaffoldMessenger.of( |
|
context, |
|
).showSnackBar(SnackBar(content: Text('读取失败: ${e.toString()}'))); |
|
} |
|
return null; |
|
} |
|
} |
|
|
|
// 移除showLoadingDialog方法,因为现在直接在调用处处理 |
|
}
|
|
|