You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I'm facing a small issue with streaming responses from an API using Dio. When I try to print the response in the console or display it in the app, the data only appears after the API completes sending everything, rather than showing updates in real-time.
i used fast api to make a streming route
`@router.post("/stream" )
async def stream():
async def generate():
for i in range(10):
await asyncio.sleep(0.5)
yield json.dumps({"response": f"This is message {i}"})
return StreamingResponse(
generate(),
media_type="application/x-ndjson"
)`
and this is the flutter code i tested
`final cancelToken = CancelToken();
final res = await dio.post<ResponseBody>(
baseUrl + routes[route]!,
options: Options(
headers: {'Authorization': 'Bearer $accessToken'},
responseType: ResponseType.stream,
receiveDataWhenStatusError: true,
),
cancelToken: cancelToken,
data: data,
);
final transformer =
StreamTransformer<String, Map<String, dynamic>>.fromHandlers(
handleData: (String chunk, EventSink<Map<String, dynamic>> sink) {
try {
final lines = chunk.split('\n');
for (final line in lines) {
if (line.trim().isEmpty) continue;
String jsonString = line;
if (line.startsWith("data: ")) {
jsonString = line.substring(6);
}
final jsonData = jsonDecode(jsonString);
sink.add(jsonData);
}
} catch (e) {
print('Error parsing chunk: $chunk');
sink.addError(e);
}
},
);
final responseStream = res.data as ResponseBody;
final stream = responseStream.stream
.cast<List<int>>()
.transform(utf8.decoder)
.transform(const LineSplitter())
.transform(transformer);
DateTime lastPrintTime = DateTime.now();
final subscription = stream.listen(
(data) {
final now = DateTime.now();
print(
'Received at ${now.difference(lastPrintTime).inMilliseconds}ms: ${data["response"]}',
);
lastPrintTime = now;
},
onError: (error) {
print('Stream error: $error');
},
onDone: () {
print('Stream completed');
},
cancelOnError: true,
);`
and this is the console output :
I/flutter (30884): Received at 4509ms: This is message 0
I/flutter (30884): Received at 3ms: This is message 1
I/flutter (30884): Received at 1ms: This is message 2
I/flutter (30884): Received at 2ms: This is message 3
I/flutter (30884): Received at 1ms: This is message 4
I/flutter (30884): Received at 1ms: This is message 5
I/flutter (30884): Received at 1ms: This is message 6
I/flutter (30884): Received at 2ms: This is message 7
I/flutter (30884): Received at 1ms: This is message 8
I/flutter (30884): Received at 1ms: This is message 9
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
-
I'm facing a small issue with streaming responses from an API using Dio. When I try to print the response in the console or display it in the app, the data only appears after the API completes sending everything, rather than showing updates in real-time.
i used fast api to make a streming route
`@router.post("/stream" )
async def stream():
async def generate():
for i in range(10):
await asyncio.sleep(0.5)
yield json.dumps({"response": f"This is message {i}"})
and this is the console output :
I/flutter (30884): Received at 4509ms: This is message 0
I/flutter (30884): Received at 3ms: This is message 1
I/flutter (30884): Received at 1ms: This is message 2
I/flutter (30884): Received at 2ms: This is message 3
I/flutter (30884): Received at 1ms: This is message 4
I/flutter (30884): Received at 1ms: This is message 5
I/flutter (30884): Received at 1ms: This is message 6
I/flutter (30884): Received at 2ms: This is message 7
I/flutter (30884): Received at 1ms: This is message 8
I/flutter (30884): Received at 1ms: This is message 9
Beta Was this translation helpful? Give feedback.
All reactions