【发布时间】:2020-03-21 13:29:15
【问题描述】:
我遇到了一个问题,将 Stream 返回到 StreamBuilder 小部件中。我正在尝试访问一个自定义类,该类存储为我在 firebase 中的用户集合中的列表,但由于某种原因,它继续返回一个空列表。
这是我的PhotoEntry 自定义类的示例:
class PhotoEntry {
final Timestamp date;
final String fileUrl;
PhotoEntry({
@required this.date,
@required this.fileUrl,
});
Map<String, dynamic> toMap() => {
'date': date.millisecondsSinceEpoch,
'fileUrl': fileUrl,
};
PhotoEntry.fromMap(Map<String, dynamic> data)
: date = new Timestamp.fromMillisecondsSinceEpoch(data['date']),
fileUrl = data['fileUrl'];
PhotoEntry.initial()
: date = Timestamp.now(),
fileUrl = 'No Photo';
}
这是给我带来麻烦的 Stream。正如我所说,它返回一个空列表:
Stream<List<PhotoEntry>> getUserPhotosStream(User user) {
if (user == null) {
return Stream.empty();
}
try {
return _db
.collection('users')
.document(user.uid)
.collection('photos')
.snapshots()
.map((list) => list.documents
.map((doc) => PhotoEntry.fromMap(doc.data))
.toList());
} catch (e) {
print(e);
rethrow;
}
}
这里使用getUserPhotosStream:
Widget _galleryPage() {
return StreamBuilder<List<PhotoEntry>>(
stream: _db.getUserPhotosStream(_user),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting ||
!snapshot.hasData) {
return Container(child: Center(child: CircularProgressIndicator()));
} else {
return ListView.builder(
scrollDirection: Axis.horizontal,
physics: BouncingScrollPhysics(),
itemCount: _user.photos.length,
itemBuilder: (context, index) {
var photo = snapshot; // For debugging
print(photo); // For dubigging
// return Card(photo)
},
);
}
},
);
}
我已经验证了集合和文档标题是正确的,并且传入的用户不为空并且包含所有正确的数据。我在这里做错了什么?
【问题讨论】:
-
so
PhotoEntry.fromMap被多次调用,但你有一个空列表? -
@pskink
PhotoEntry.fromMap仅在将我的地图转换为列表时被调用一次。但是,是的,这是一个空列表。 -
你在哪里使用
getUserPhotosStream方法?发布您的StreamBuilder的代码 -
@pskink 编辑了我的原始帖子以包含
StreamBuilder -
似乎
itemCount: _user.photos.length不正确-您必须根据snaphot.data获得计数
标签: firebase flutter dart google-cloud-firestore stream