Using AngularDart and Firebase, the below code doesn't work because yield
is inside an anonymous inner class. How might I rewrite this? I'm new to both Angular and Dart and couldn't find any examples for this.
Essentially I'm trying to listen for items inside a stream in my service, but I'm getting the actual item from firebase and need to pass these firebase items back to the stream.
In the service:
Stream<Item> itemStream() async* {
final ref = database().ref("items");
await ref.onChildAdded.listen((e) {
DataSnapshot snapshot = e.snapshot;
Map parsedMap = snapshot.val();
String id = snapshot.key;
String property1 = parsedMap['property1'];
String property2 = parsedMap['property2'];
print(property1);
print(property2);
yield new Item(id, property1, property2); // invalid; yield does not work here.
});
// yield works here but it's no use here.
}
Component:
var stream = itemListService.itemStream();
await for (var item in stream) {
print(item.id);
}
Update: I got around this by not using a service. However I thought using a service was better practice so that's why I wanted to do it.
You could do two things.
1) Use a StreamController
2) (Better)
Stream<Item> itemStream() {
final ref = database().ref("items");
return ref.onChildAdded.map((e) {
DataSnapshot snapshot = e.snapshot;
Map parsedMap = snapshot.val();
String id = snapshot.key;
String property1 = parsedMap['property1'];
String property2 = parsedMap['property2'];
print(property1);
print(property2);
return new Item(id, property1, property2);
}