I am integrating a chat feature in my mobile application, and decided to use Firebase Realtime Database for the backend instad of Firestore as a cost reduction mechanism. I am running into a problem, however. There seems to be very sparse documentation on how to create infinite scrolling using data from Realtime Database
instead of Firestore
.
Below is the organization of my chat messages. This is the query I want to use:
FirebaseDatabase.instance
.ref("messages/${widget.placeID}")
.orderByChild("timeStamp")
And this is the widget I want to return for each result:
MessageWidget(
message: message.text,
id: message.uid,
name: message.name,
lastSender: message.lastSender,
date: message.timeStamp,
profilePicture: message.profilePicture,
);
Here is the database structure
The query works, and I have already programmed the MessageWidget from the JSON response of the query. All I need is for the query to be called whenever it reaches the top of its scroll, and load more MessageWdiget
s. Also note, this is a chat app where users are scrolling up, to load older messages, to be added above the previous.
Thank you!
EDIT: here is the code I currently have:
Flexible(
child: StreamBuilder(
stream: FirebaseDatabase.instance
.ref("messages/${widget.placeID}")
.orderByChild("timeStamp")
.limitToLast(20)
.onValue,
builder:
(context, AsyncSnapshot<DatabaseEvent> snapshot) {
if (!snapshot.hasData) {
return const CircularProgressIndicator();
} else {
Map<dynamic, dynamic> map =
snapshot.data!.snapshot.value as dynamic;
List<dynamic> list = [];
list.clear();
list = map.values.toList();
return Align(
alignment: Alignment.bottomCenter,
child: Padding(
padding: const EdgeInsets.only(bottom: 20),
child: ListView.builder(
controller: _scrollController,
// shrinkWrap: true,
itemCount: list.length,
itemBuilder: (context, index) {
final json = list[index]
as Map<dynamic, dynamic>;
final message = Message.fromJson(json);
return MessageWidget(
message: message.text,
id: message.uid,
name: message.name,
lastSender: message.lastSender,
date: message.timeStamp,
profilePicture:
message.profilePicture,
);
}),
),
);
}
},
),
),
My initState
void initState() {
super.initState();
_scrollController.addListener(() {
if (_scrollController.position.atEdge) {
bool isTop = _scrollController.position.pixels == 0;
if (isTop) {
//add more messages
} else {
print('At the bottom');
}
}
});
}
2
Answers
After several days of testing code, I came up with the following solution
The first step is to declare a
ScrollController
in your state class.You will also need to declare a
List
to store query resultsNext, use the following function to get initial data
Run this in
initState
Now to display the initial data that was generated when the page was loaded, build the results into a
ListView
Note that your
ListView
must be constrained, meaning that you can scroll to the beginning or end of yourListView
. Sometimes, theListView
won't have enough data to fill and be scrollable, so you must declare a height with aContainer
or bound it to its contents.Now you have the code that fetches data when the page is loaded using
getStartData()
andinitState
. The data is stored inlist
, and aListView.builder
builds aMessageWidget
for each item returned bygetStartData
. Now, you want to load more information when the user scrolls to the top.Then, make the function run when the
ListView.builder
is scrolled all the way to the top by adding this to the already existinginitState
.Hopefully this helps or gives you a pointer on where to go from here. Thanks to Frank van Puffelen for his help on which query to use based on the previous answer.
Your code already loads all messages.
If you want to load a maximum number of messages, you’ll want to put a limit on the number of messages you load. If you want to load only the newest messages, you’d use
limitToLast
to do so – as the newest messages are last when you order them by theirtimeStamp
value.So to load for example only the 10 latest messages, you’d use:
This gives you the limited number of messages to initially show in the app.
Now you need to load the 10 previous messages when the scrolling reaches the top of the screen. To do this, you need to know the
timeStamp
value and the key of the message that is at the top of the screen – so of the oldest message you’re showing so far.With those two values, you can then load the previous 10 with:
The database here again orders the nodes on their
timeStamp
, it then finds the node that is at the top of the screen based on the values you give, and it then returns the 10 nodes right before that.