将数据存储到Firebase数据库后,我尝试获取新创建的文档ID,但出现错误

E/flutter (20333): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The method 'listen' was called on null.
E/flutter (20333): Receiver: null
E/flutter (20333): Tried calling: listen(Closure: (String) => void)

send_data_bloc
 _repository
          .addOrder(order)
          .listen((documentId) => print(documentId));

存储库
@override
  Observable<String> addOrder(Order order) {
      var a = endpoints.collectionEndpoint.add(order.toJson());
      a.then((val) {
        return Observable.fromFuture(val.documentID());
      });

端点
  @override
  get collectionEndpoint => _firestore
      .collection(collectionName)
      .document(this.id)
      .collection(orderCollectionName);

最佳答案

理想情况下,您应该从存储库中返回 future ,并等待集团中的 future 。让我尝试在此处提供完整的代码段。就像这样:

send_data_bloc

final documentId = await _repository
      .addOrder(order);
print(documentId);
return documentId;

存储库
@override
Future<String> addOrder(Order order) {
  return endpoints.collectionEndpoint.add(order.toJson());

端点
@override
get collectionEndpoint => _firestore
  .collection(collectionName)
  .document(this.id)
  .collection(orderCollectionName);

10-08 07:26