I am building a chat app, and I am using Laravel and flutter, I am continually sending requests to Laravel every second using streams to get new messages if any from the backend. The problem is whenever I receive a new message the UI reloads. Is there a way I can receive the replies without reloadind the UI or jump the step of snapshot.dat == null?. Here is my Code.
// A future for fetching user messages which is called every second to return messages between users
Future<List<Messages?>?> reFetchUserMessages() async {
var readMessages = await showReadMessages(roomId);
userMessage = await showRoom(roomId);
// Read user messages
return userMessage;
}
// A stream which calls our future every second to return messages between users
Stream<List<Messages?>?> getUserMessages() =>
Stream.periodic(const Duration(seconds: 1))
.asyncMap((_) => reFetchUserMessages());
Here is where I am building my UI according to snapshot data.
// Streambuilder for fetching user messages at intervals of 1 second
body: StreamBuilder(
initialData: userMessage,
stream: getUserMessages(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.data == null) {
return const Center(
child: CircularProgressIndicator(
color: Color.fromARGB(255, 214, 123, 18)));
} else if (snapshot.data.toString() == [].toString()) {
return const Center(
child: Text('No Messages.'),
);
}
var userMessages = snapshot.data as List<Messages>;
// Text sender chat bubble
getSenderView(CustomClipper clipper, BuildContext context,
index) =>
// If messages has children return a column of the parent and children
userMessages[index].text!.children?.length != null
? Column(
children: [
// Chat bubble for parent of sender with children under it
// If there is no reply return normal chat bubble
userMessages[index].quotes == null
? OwnMessageCard(
message: userMessages[index]
.text!
.message
.toString(),
time: Jiffy(userMessages[index]
.createdAt
.toString())
.fromNow())
:
// Reply chat bubble
SenderReply(
time: userMessages[index]
.createdAt
.toString(),
reply: getUserReplies(
userMessages,
userMessages[index].parent,
userMessages[index].quotes),
message: userMessages[index]
.text!
.message
.toString()),
The chat app working fine, but whenever I receive a message, it reloads which I beleive is not a good user experience. Somebody please assisst.