fetch static method
Download a single financial data file.
Implementation
static Future<bool> fetch({
required String downloadDir,
required String filename,
void Function(int count, int blockSize)? onProgress,
}) async {
final server = gpHosts.first;
final client = TdxSocketClient();
try {
final ok = await client.connect(server.host, server.port);
if (!ok) return false;
await client.setup();
// Download file in chunks
final filePath = '$downloadDir/$filename';
final dir = Directory(downloadDir);
if (!dir.existsSync()) {
dir.createSync(recursive: true);
}
final file = File(filePath);
final sink = file.openWrite();
int offset = 0;
while (true) {
final chunk = await client.getReportFile(filename, offset);
if (chunk.isEmpty || chunk.length <= 1) break;
// First 2 bytes indicate chunk size
if (chunk.length > 2) {
final data = Uint8List.view(
chunk.buffer, chunk.offsetInBytes + 2, chunk.length - 2);
if (data.isEmpty) break;
sink.add(data);
offset += data.length;
onProgress?.call(offset, 0);
} else {
break;
}
}
await sink.flush();
await sink.close();
return true;
} finally {
client.disconnect();
}
}