在flutter开发过程中,我们会遇到耗时不少操作,比如文件写入或数据导出等。今天这篇文章以文件写入为引子,简述如何使用Isolate开启线程,在其中进行耗时操作,从而避免阻塞 UI 线程。
一、获取存储文件路径
既然是存储文件,首先要获取文件的存储地址。示例代码如下:
/// 获取文件存储路径
static Future<File> getLocalSupportJSONFile(String fileName) async {
String filePath = "";
var dir = await getExternalStorageDirectory();
if (dir == null) return File("");
// handler是子目录
Directory directory = Directory('${dir.path}/handler');
if (!directory.existsSync()) {
directory.createSync();
}
// 存储json文件
filePath = '${directory.path}/$fileName.json';
return File(filePath);
}
这里我是存储到Android端本地目录,如果是IOS端建议使用getApplicationDocumentsDirectory().
二、初始化线程
接下来使用Isolate开启线程写入数据。
late File saveFile;
ReceivePort receivePort = ReceivePort();
SendPort? _sendPort;
List<dynamic> buffer = []; // 临时缓存
// 定时写入缓存
late Timer timer;
/// 初始化文件并启动子线程
Future<

最低0.47元/天 解锁文章
1411

被折叠的 条评论
为什么被折叠?



