使用Firestore和Flutter从子集合中查询特定文档

时间:2019-11-13 05:17:30

标签: flutter google-cloud-firestore

我要执行的操作是使用“文档ID”查询特定文档。但是查询出现为空。这是我的代码。

 void getEquipDetail() async {
    await _firestore
        .collection('users')
        .document(_userUid)
        .collection('equipment')
        .document(documentID)
        .get()
        .then((DocumentSnapshot ds) {
      equipName = ds.data['equip_name'];
      print(equipName);
    });
  }

当我将“设备”作为根级别的集合时,这很好用,但是由于将其作为“用户”的子集合,所以我无法查询特定文档。

这是当前的数据库结构 -collection(用户)*根级别   -document(用户ID)     -集合(设备)       -document(设备文档)*这是我正在尝试查询的内容

这是返回的错误

[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
Receiver: null
Tried calling: []("equip_name")
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1      _EquipmentDetailScreenState.getEquipDetail.<anonymous closure> (package:simmanager/screens/equip_detail_screen.dart:52:26)
#2      _rootRunUnary (dart:async/zone.dart:1132:38)
#3      _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#4      _FutureListener.handleValue (dart:async/future_impl.dart:137:18)
#5      Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:678:45)
#6      Future._propagateToListeners (dart:async/future_impl.dart:707:32)
#7      Future._completeWithValue (dart:async/future_impl.dart:522:5)
#8      _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:30:15)
#9      _completeOnAsyncReturn (dart:async-patch/async_patch.dart:288:13)
#10     DocumentReference.get (package:cloud_firestore/src/document_reference.da<…>

这是可以正常工作的代码(用于物品而不是设备)

void getItemDetail() async {
    await Firestore.instance
        .collection('items')
        .document(widget.item.document)
        .get()
        .then((DocumentSnapshot snapshot) {
      itemDetails = snapshot.data;
      itemName = snapshot['item_name'];
      itemNum = snapshot['item_num'.toString()];
      itemDesc = snapshot['item_desc'];
      itemLoc = snapshot['item_location'];
      itemQty = snapshot['item_qty'.toString()];
      itemUom = snapshot['item_uom'];
      itemMfr = snapshot['item_mfr'];
      itemStock = snapshot['out_of_stock'];
      lastEditDate = snapshot['edit_date'];
      createDate = snapshot['create_date'];
      imageURL = snapshot['image_url'];

1 个答案:

答案 0 :(得分:0)

您在第一个示例中的代码与第二个示例中的代码实际上不匹配。请仔细比较它们。对于第一个示例,您似乎要说:

equipName = ds['equip_name'];