Flutter 代码优化:接收数据后关闭定时器并清空 xdata
try {
Response response = await Dio().post(
'http://127.0.0.1:5000/test',
options: Options(
responseType: ResponseType.stream,
),
);
int current = 1;
bool end = false;
Timer timer;
timer = Timer.periodic(Duration(seconds: 1), (timer) {
if (end) {
timer.cancel();
}
if (current == 0) {
current = 1;
setState(() {});
} else {
current--;
print(current);
}
});
final textMessage = types.TextMessage(
author: types.User(id: '131231-322-4a89-ae75-a22bf8d6f3ac'),
createdAt: DateTime.now().millisecondsSinceEpoch,
id: const Uuid().v4(),
text: xdata,
);
response.data.stream.transform(StreamTransformer<Uint8List, String>.fromHandlers(
handleData: (data, sink) {
if (data.isNotEmpty) {
sink.add(utf8.decode(data));
}
},
)).listen((data) {
xdata += data;
print(data);
if (data.isEmpty) {
end = true;
xdata = '';
timer.cancel();
}
Global.messages[0] = types.TextMessage(
author: types.User(id: '131231-322-4a89-ae75-a22bf8d6f3ac'),
createdAt: DateTime.now().millisecondsSinceEpoch,
id: const Uuid().v4(),
text: xdata,
);
});
Global.messages_pure += ' AI: '' + response.data.toString() + '';';
} on DioError catch (e) {
if (e.type == DioErrorType.connectTimeout || e.type == DioErrorType.receiveTimeout) {
} else {
print(e);
}
}
代码说明:
- 使用
Dio库发送POST请求,并设置responseType为ResponseType.stream,以接收数据流。 - 使用
Timer.periodic创建一个定时器,每秒执行一次,并在数据接收完毕后关闭定时器。 - 使用
StreamTransformer将Uint8List数据流转换为String数据流。 - 在
listen方法中,将接收到的数据追加到xdata中,并判断是否为最后一条数据。 - 如果是最后一条数据,则将
end设置为true,并清空xdata。 - 使用
timer.cancel()关闭定时器。
代码优化:
- 使用
data.isNotEmpty判断是否为最后一条数据,避免重复代码。 - 使用
timer.cancel()关闭定时器,释放资源。
使用场景:
该代码适用于需要接收数据流,并在数据接收完毕后执行特定操作的场景,例如聊天应用、文件下载等。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/n7Q3 著作权归作者所有。请勿转载和采集!