'How to get Server Sent Events in my Flutter app?

I'm trying to receive SSE data as JSON in my Flutter app. But instead of getting the data I'm getting the following repeated arrays of numbers in my console.

    I/flutter (17286): Received streamedResponse.statusCode:200
    I/flutter (17286): Received data:[100, 97, 116, 97, 58, 32, 123, 34, 109, 115, 103, 34, 58, 34, 84, 104, 105, 115, 32, 105, 115, 32, 109, 121, 32, 109, 101, 115, 115, 97, 103, 101, 34, 125, 10, 10]
    I/flutter (17286): Received data:[100, 97, 116, 97, 58, 32, 123, 34, 109, 115, 103, 34, 58, 34, 84, 104, 105, 115, 32, 105, 115, 32, 109, 121, 32, 109, 101, 115, 115, 97, 103, 101, 34, 125, 10, 10]

Here's what the SSE data looks like on the server

data: {"msg":"This is my message"}
data: {"msg":"This is my message"}
data: {"msg":"This is my message"}
    (repeated over and over)

And here's the Flutter code;

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

 class MyApp extends StatelessWidget {
 http.Client _client;

  MyApp() : super() {
         subscribe();
   }

  @override
    Widget build(BuildContext context) {
       return MaterialApp(
     title: 'Flutter SSE',
     home: Scaffold(
      appBar: AppBar(
      title: Text('Receive SSE Events'),
    ),
    body: Center(
      child: Text('Ready for events..'),
    ),
   ),
 );
}

subscribe() async {
  print("Subscribing..");
  try {
   _client = http.Client();

  var request = new http.Request("GET", Uri.parse("http://18.224.97.18:8080/connect"));
  request.headers["Cache-Control"] = "no-cache";
  request.headers["Accept"] = "text/event-stream";

  Future<http.StreamedResponse> response = _client.send(request);

  response.asStream().listen((streamedResponse) {
    print("Received streamedResponse.statusCode:${streamedResponse.statusCode}");
    streamedResponse.stream.listen((data) {
      print("Received data:$data");
    });

  });
} catch(e) {
  print("Caught $e");
  }
}

 unsubscribe() {
   _client.close();
      }
     }

I'm not sure why "print("Received data:$data") is giving arrays of numbers instead of the {"msg":"This is my message"} in the SSE stream.

Anyone know why I'm getting these numbers instead of the data?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source