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