I try to implement a chat system in flutter with a back-end in asp.net core and a connection in real-time via SignalR.
The goal is when I open a chat room, all messages previously sended are loaded in the chat room, for this purpose, I call a method in the back-end called "Connect". Once the "Hub" is hit, it calls my front-end method and send back a list of messages, this flow is correct and working but I encountered a problem when I want to display the messages in flutter, here is how I tried to do it with the help of StreamBuilder :
class GrpMessage extends StatefulWidget {
final GrpMessages group;
final HubConnection connection;
GrpMessage({Key key, @required this.group, @required this.connection})
: super(key: key);
@override
_GrpMessageState createState() => _GrpMessageState();
}
class _GrpMessageState extends State<GrpMessage> {
List<Messages> listMessages = new List();
final webSocketStream = BehaviorSubject<List<Messages>>();
@override
void initState() {
super.initState();
connect();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Center(child: Text(widget.group.name))),
body: testSocket()
);}
connect() async {
await widget.connection
.invoke("Connect", args: <Object>[widget.group.idEvent]);
widget.connection.on("ReceiveGroupMsg", grpReceived);
}
grpReceived(List<Object> parameters) {
List<dynamic> msg = parameters[0];
for (dynamic msg in msg) {
listMessages.add(Messages.fromJson(msg));
}
webSocketStream.sink.add(listMessages);
}
Widget testSocket() {
return StreamBuilder<List<Messages>>(
stream: webSocketStream.stream,
initialData: listMessages,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
MessagesList(messages: snapshot.data),
]);
} else if (snapshot.hasError) {
return Center(child: Text("No messages to display"));
}
return Center(
child: CircularProgressIndicator(
backgroundColor: Theme.of(context).primaryColor));
});
}
MessagesList is another widget, it renders fine but the code is not relevant so I won't post it :) I feel like I'm missing something with the stream stuff, I would expect when I add the listMessages in the stream that the stream would then display the messages but it does not (even tho the listMessages is correctly populated with the data from the back-end).
I'm new to Flutter to It's surely a mistake from me, If someone could point me what I'm doing wrong, it'd be very helpful !
Thanks in advance,
Lio
So I found the answer... The library that I use for Signal R mention that I have to await when I call a method from the server, I had to remove the await and then it worked fine. Thanks to Saed for his help !