Reputation: 6368
I'm very new to flutter Streams/Bloc/Provider and I'm following a tutorial to understand it. In the tutorial dough they use Firestore so they get a Stream like this:
Stream<List<Todo>> todos() {
return todoCollection.snapshots().map((snapshot) {
return snapshot.documents
.map((doc) => Todo.fromEntity(TodoEntity.fromSnapshot(doc)))
.toList();
});
}
Where their snapshot is List<DocumentSnapshot>
, mine from RTDB
is instead an Event.
I'm trying to get a Stream<List<Object>>
from a RTDB
node, but from the .onValue()
property I get a Stream<Event>
.
Inside the async
map()
I access the snapshot
Event but I don't get access to the Dart.core
's map()
as in the example that uses Firestore
, for it's not a List.
alerts()
is the Stream that the bloc
will be listening to but it's expecting a Stream<List<Object>>
and I can't get it.
How would I go to map it to a Stream<List<Object>>
as I need?
Thank you very much for your time and help.
My code is:
//
static UserAlert fromSnapshot(DataSnapshot snapshot) {
return UserAlert(
city: snapshot.value['City'],
country: snapshot.value['Country'],
date: snapshot.value['Date'],
description: snapshot.value['Description'],
id: snapshot.value['Id'],
latitude: snapshot.value['Latitude'],
longitude: snapshot.value['Longitude'],
region: snapshot.value['Region'],
timestamp: snapshot.value['Timestamp'],
alertImageName: snapshot.value['alertImageName'],
imageUrl: snapshot.value['imageUrl'],
user: snapshot.value['user']);
}
// try 1
Stream<List<UserAlert>> alerts() {
return _databaseReference.onValue.map((snapshot) {
// do the mapping to a Stream<List<UserAlert>>
});
}
// try 2
Stream<List<UserAlert>> alerts() {
return _databaseReference.onValue.toList(){ // Function expressions can't be named error
};
}
// try 3
Stream<List<UserAlert>> alerts() {
return _databaseReference.onValue.map(
(snapshot) => UserAlert.fromSnapshot(snapshot); // wrong return type
);
}
Upvotes: 1
Views: 1783
Reputation: 3488
Use StreamTransformer
Stream<UserAlert> alerts() {
handleData(Event event, EventSink<UserAlert> sink) =>
sink.add(UserAlert.fromSnapshot(event.snapshot.value));
final transformer =
StreamTransformer<Event, UserAlert>.fromHandlers(handleData: handleData);
return _databaseReference.onValue.transform(transformer);
}
Upvotes: 1