postStreamRaw method
Make a POST request and return raw stream for JSON array streaming
Implementation
Stream<String> postStreamRaw(
String endpoint,
Map<String, dynamic> data,
) async* {
try {
final fullEndpoint = _getEndpointWithAuth(endpoint);
final response = await dio.post(
fullEndpoint,
data: data,
options: Options(
responseType: ResponseType.stream,
headers: {'Accept': 'application/json'},
),
);
// Handle ResponseBody properly for streaming
final responseBody = response.data;
Stream<List<int>> stream;
if (responseBody is Stream<List<int>>) {
stream = responseBody;
} else if (responseBody is ResponseBody) {
stream = responseBody.stream;
} else {
throw Exception(
'Unexpected response type: ${responseBody.runtimeType}');
}
// Use UTF-8 stream decoder to handle incomplete byte sequences
final decoder = Utf8StreamDecoder();
await for (final chunk in stream) {
final decoded = decoder.decode(chunk);
if (decoded.isNotEmpty) {
yield decoded;
}
}
// Flush any remaining bytes
final remaining = decoder.flush();
if (remaining.isNotEmpty) {
yield remaining;
}
} on DioException catch (e) {
logger.severe('Stream request failed: ${e.message}');
rethrow;
}
}