如何将权限错误转换为 firebase 流上的“空”事件?

How to transform permission errors into `null` events on a firebase stream?

如果我的流中有错误,我想发出 null

在下面的简化示例中,用户可能没有访问文档的权限,在这种情况下,null 是适合我的应用程序的流事件。

Stream<String?> idOrNull() {
  return FirebaseFirestore.instance
    .doc('collection/doc')
    .snapshots()
    // ...if there's an error, I want to emit `null`
    .map((DocumentSnapshot<Map<String, dynamic>> snap) {
      return snap.id;
    });
}

阅读 Stream : handleError method 文档,有一条不太有用的建议:

If you need to transform an error into a data event, use the more generic Stream.transform to handle the event by writing a data event to the output sink.

查看 Stream.transform,我仍然对如何完成这项任务一无所知。非常感谢您的建议。

StreamTransformer 可以在处理错误时访问流接收器,所以这是可行的:

Stream<String?> idOrNull() {
  return FirebaseFirestore.instance
    .doc('collection/doc')
    .snapshots()
    .transform(
      StreamTransformer<DocumentSnapshot<Map<String, dynamic>>,
          String?>.fromHandlers(
        handleData: (snapshot, sink) {
          sink.add(snapshot.id);
        },
        handleError: (error, stackTrace, sink) {
          sink.add(null);
        },
      ),
    );
}