Reputation: 3730
I'm creating a chat app in flutter using firebase , but i'm facing issues with getting data from realtime database , it is public chat , i'm not sure what is wrong that the data is not fetched , if anyone could help , i ll deeply appreciate it , thank you
Stream<Event> getMessages() {
DatabaseReference databaseReference = FirebaseDatabase(databaseURL: databaseUrl).reference().child('Messages');
return databaseReference.onValue;
}
Expanded(child: Container(
child: StreamBuilder<Event>(
stream: AuthService().getMessages(),
builder: (context,data){
if(data.hasError){
return Center(
child: Text("No data 1"),
);
}
if(data.connectionState == ConnectionState.done){
if(data.data!.snapshot.exists){
print("data is in done" );
Map<String,dynamic> values = data.data!.snapshot.value;
for(var child in values.values){
var receiverName = child['userName'];
var receiverMessage = child['message'];
var receiverImageUrl = child['imageUrl'];
return Container(
child: Container(
child: Row(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: CircleAvatar(
radius: 30,
backgroundColor: Colors.transparent,
backgroundImage: NetworkImage(receiverImageUrl),
),
),
Expanded(
child: Column(
children: [
Text(receiverName),
Text(receiverMessage)
],
),
)
],
),
),
);
}
}
}
return Center(
child: Text("No data 2"),
);
},
),
)),
Upvotes: 0
Views: 426
Reputation: 598807
Two problems in your code.
First up you're reading the entire database, only to use the Messages
node. I recommend updating that to:
Stream<Event?> getMessages() {
DatabaseReference databaseReference = FirebaseDatabase(databaseURL: databaseUrl).reference().child('Messages');
return databaseReference.onValue;
}
Second, since you're reading Messages
your data.data!.snapshot
will have multiple messages. So calls like data.data!.snapshot.value['userName']
won't work, because you don't say what message to read the userName
from.
You'll want to loop through data.data!.snapshot.value.values
to then get ['userName']
on the specific child snapshot it.
Upvotes: 2