Flutter 使用 Dio 接收流式传输文本并实时显示
使用 Dio 接收流式传输的文字可以通过使用 Dio 的 stream 方法来实现,具体代码如下:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
class StreamTextPage extends StatefulWidget {
@override
_StreamTextPageState createState() => _StreamTextPageState();
}
class _StreamTextPageState extends State<StreamTextPage> {
String _text = '';
@override
void initState() {
super.initState();
_getTextStream().listen((data) {
setState(() {
_text = utf8.decode(data);
});
});
}
Stream<List<int>> _getTextStream() async* {
final dio = Dio();
final response = await dio.get('http://127.0.0.1:9000/?content=%E7%BB%99%E6%88%91%E5%86%99%E4%B8%80%E7%AF%87300%E5%AD%97%E7%9A%84%E6%96%87%E7%AB%A0%EF%BC%8C%E5%85%B3%E4%BA%8E%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD', options: Options(responseType: ResponseType.stream));
yield* response.data.stream();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Stream Text'),
),
body: Center(
child: Text(_text),
),
);
}
}
在上面的代码中,我们通过使用 Dio 的 stream 方法来获取流式传输的数据,然后使用 StreamBuilder 来实时更新 Text 的内容。需要注意的是,在获取数据时需要设置 options 的 responseType 为 ResponseType.stream,否则会无法获取到流式传输的数据。
原文地址: https://www.cveoy.top/t/topic/nMtj 著作权归作者所有。请勿转载和采集!