How to have Similar functionality as Server-Sent-Event / EventSource functionality in Flutter?

Viewed 839

I have a web developer background, just a beginner in Flutter and Dart.

For a project, I need to implement Server-Sent-Event / EventSource functionality in Flutter.

I have searched for options like dart:http EventSource constructor and Flutter StreamBuilder but I have not found a working example with API.

Can you give me some examples where the Flutter app can listen to an API?

This is what do in Web development.

// client side

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

// 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', () => {})
})

1 Answers

This code maybe helpful

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