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);
  }
}

代码说明:

  1. 使用 Dio 库发送 POST 请求,并设置 responseType 为 ResponseType.stream,以接收数据流。
  2. 使用 Timer.periodic 创建一个定时器,每秒执行一次,并在数据接收完毕后关闭定时器。
  3. 使用 StreamTransformer 将 Uint8List 数据流转换为 String 数据流。
  4. 在 listen 方法中,将接收到的数据追加到 xdata 中,并判断是否为最后一条数据。
  5. 如果是最后一条数据,则将 end 设置为 true,并清空 xdata。
  6. 使用 timer.cancel() 关闭定时器。

代码优化:

  • 使用 data.isNotEmpty 判断是否为最后一条数据,避免重复代码。
  • 使用 timer.cancel() 关闭定时器,释放资源。

使用场景:

该代码适用于需要接收数据流,并在数据接收完毕后执行特定操作的场景,例如聊天应用、文件下载等。