![](/img/trans.png)
[英]Is a Stream<List<Object>> from Firebase snapshot returning the entire node at every change in the node? Flutter
[英]Getting a Stream<List<Object>> from a Stream<Event> from firebase real time database Flutter
我對 flutter Streams/Bloc/Provider 很陌生,我正在按照教程來理解它。 在教程面團中,他們使用 Firestore,因此他們獲得了這樣的 Stream:
Stream<List<Todo>> todos() {
return todoCollection.snapshots().map((snapshot) {
return snapshot.documents
.map((doc) => Todo.fromEntity(TodoEntity.fromSnapshot(doc)))
.toList();
});
}
他們的快照是List<DocumentSnapshot>
,我的來自RTDB
是一個Event.
我正在嘗試從RTDB
節點獲取Stream<List<Object>>
,但是從.onValue()
屬性我得到了Stream<Event>
。 在async
map()
我訪問了snapshot
事件,但在使用Firestore
的示例中,我無法訪問Dart.core
的map()
,因為它不是列表。 alerts()
是該bloc
將要偵聽的 Stream,但它期待一個Stream<List<Object>>
而我無法得到它。 我將如何根據需要將其映射到Stream<List<Object>>
? 非常感謝您的時間和幫助。 我的代碼是:
//
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
);
}
使用流轉換器
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.