I'm having an issue with StreamBuilder and ListView.
My initial build works as intended, loading all nodes from my DB and adding them to ListView:
--Node 1 --Node 2 --Node 3
However, when a new node is added to the DB (Node 4), the StreamBuilder recognizes the change and appends the entire list of nodes to the ListView, resulting a duplicate data:
--Node 1 --Node 2 --Node 3 --Node 1 --Node 2 --Node 3 --Node 4
class _HomeScreenState extends State<HomeScreen> {
DatabaseReference usersChatsRef =
FirebaseDatabase().reference().child('users-chats');
@override
void initState() {
super.initState();
Stream<List<UsersChats>> getData(User currentUser) async* {
var usersChatsStream = usersChatsRef.child(currentUser.uid).onValue;
var foundChats = List<UsersChats>();
await for (var userChatSnapshot in usersChatsStream) {
Map dictionary = userChatSnapshot.snapshot.value;
if (dictionary != null) {
for (var dictItem in dictionary.entries) {
UsersChats thisChat;
if (dictItem.key != null) {
thisChat = UsersChats.fromMap(dictItem);
} else {
thisChat = UsersChats();
}
foundChats.add(thisChat);
}
}
yield foundChats;
}
}
}
@override
Widget build(BuildContext context) {
final user = Provider.of<User>(context);
return Scaffold(
appBar: AppBar(),
body: StreamBuilder<List<UsersChats>>(
stream: getData(user),
builder:
(BuildContext context, AsyncSnapshot<List<UsersChats>> snap) {
if (snap.hasError || !snap.hasData)
return Text('Error: ${snap.error}');
switch (snap.connectionState) {
case ConnectionState.waiting:
return Text("Loading...");
default:
return ListView.builder(
itemCount: snap.data.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(snap.data[index].id),
subtitle: Text(snap.data[index].lastUpdate),
);
},
);
}
}),
);
}
}
class UsersChats {
String id;
String lastUpdate;
UsersChats(
{this.id,
this.lastUpdate});
factory UsersChats.fromMap(MapEntry<dynamic, dynamic> data) {
return UsersChats(
id: data.key ?? '',
lastUpdate: data.value['lastUpdate'] ?? '');
}
}
I'm referencing the stream outside of the build method because I need to perform multiple async functions on the stream (as discussed in this thread How do I join data from two Firestore collections in Flutter?).
Any help would be greatly appreciated!