I have the logic figured and it works but I'm missing something because the only way this works is when I replace the array with the next "page" or documents but when I do a .addAll()
to it, it gets messy. The same first documents get readded and a few new ones gets included as well but not all that was supposed to be included.
Code :
ScrollController _scrollController = ScrollController();
List<Message> _messages = [];
List<dynamic> _startAfter = [DateTime.now()];
...
@override
void initState() {
super.initState();
this._scrollController.addListener(() {
if (this._scrollController.position.minScrollExtent + this._scrollController.position.pixels <= -15.0) {
setState(() {
this._startAfter = [this._messages.first.createdAt.toDate()];
});
}
});
}
...
Column(
children: <Widget>[
Expanded(
child: StreamBuilder<List<Message>>(
stream: APIs().chats.messagesStream(chatID: widget.chat.chatID, orderBy: 'createdAt', descending: true, startAfter: this._startAfter, limit: 10),
builder: (context, snapshot) {
print(this._startAfter);
switch (snapshot.connectionState) {
case ConnectionState.waiting:
{
return PAIndicator();
}
default:
{
if (snapshot.hasData) {
this._messages = snapshot.data; // Having the issue here.
// this._messages.addAll(snapshot.data); Causes problems when rebuilding
return MessagesList(
scrollController: this._scrollController,
messages: this._messages,
aUser: widget.aUser,
);
} else {
return ListView();
}
}
}
}),
),
// ...
]
)
I noticed the bug only happens when it's being rebuilt.
When the data is retrieved it replaces what's in the array, how can I just append the data instead of just replacing it or giving multiple same values of the same messages when the .addAll()
is used without worry of the ui being rebuilt, like if the keyboard shows and closes?
Also, how can I make sure that if there are no more documents it doesn't get rebuilt or calls firebase? (Solved it, now just the main question above is left)