I'm trying to get message from an API I builed in express in Flutter.
The thing is, to get my messages I had the build a streambuilder beacause I want the list of message to update on new messages. To achieve this, a create a steam method that check the API every x seconds.
Stream<List<Message>> streamMessage() async* {
final storage = FlutterSecureStorage();
var json = (await storage.read(key: 'user'))!;
User user = User.fromJson(jsonDecode(json));
jwt = user.jwt;
yield* Stream.periodic(const Duration(seconds: 3), (_) async {
http.Response response = await http.get(
Uri.parse("https://myapi.com/messages"),
headers: {
'Authorization': 'Bearer $jwt',
});
List<Message> messages = [];
if (response.statusCode == 200) {
var list = List.from(jsonDecode(response.body)).reversed;
messages = list.map((e) => Message.fromJson(e)).toList();
} else {
log("Error : ${response.statusCode} -- ${response.reasonPhrase}");
}
return messages;
}).asyncMap(
(value) async => await value,
);
}
It work, but it have a lot of issues.
- the update is not as fast as I want
- it's a lot of request for nothing
- the API can easily get overloaded
- This way look more like a workaround than a real function
I would like to create a mechanisme in my backend to act more like a real stream subscibtion. As it work with Firebase. But I have no clues how it work, or even what to search.
If you have any hint, how can I achieve this ?