如何在 Flutter 中拥有与 Server-Sent-Event / EventSource 功能类似的功能?

kal*_*lis 5 flutter

我有 Web 开发背景,只是 Flutter 和 Dart 的初学者。

对于一个项目,我需要在 Flutter 中实现 Server-Sent-Event / EventSource 功能。

我搜索了 dart:http EventSource 构造函数和 Flutter StreamBuilder 等选项,但没有找到 API 的工作示例。

您能给我一些 Flutter 应用程序可以监听 API 的示例吗?

这就是 Web 开发中要做的事情。

// client side

const eventSource = new EventSource(`/eventSource/${xyz}`)
eventSource.onmessage = function(e) {
    const data = JSON.parse(e.data)
    console.log(e)
}
Run Code Online (Sandbox Code Playgroud)

// server side

router.get('/eventSource/:id', (req, res) => {
    const headers = {
        'Content-Type': 'text/event-stream',
        'Connection': 'keep-alive',
        'Cache-Control': 'no-cache'
    }
    res.writeHead(200, headers)  
    const data = `data: ${JSON.stringify(someData)}\n\n`
    setInterval(() => {
        x.write(data)
    }, 3000)
    req.on('close', () => {})
})
Run Code Online (Sandbox Code Playgroud)

kal*_*lis 4

这段代码可能有帮助

var _client;
var _streamResponse;

Future<dynamic> streamFiles() async {
  _client = http.Client();
  final url = 'url';
  var headers = {};

  final req = http.Request('GET', Uri.parse(url));
  req.headers.addAll(headers);
  final res = await _client.send(req);

  _streamResponse = res.stream.toStringStream().listen((value) {
    print(json.decode(value));
  });
}

@override
void dispose() {
  if (_streamResponse != null) _streamResponse.cancel();
  if (_client != null) _client.close();
  super.dispose();
}
Run Code Online (Sandbox Code Playgroud)