首页 > 解决方案 > 无法从 Firestore 集合的子集合中查询文档

问题描述

我正在尝试查询嵌套在 collection'users/document'useruid'/collection'items'/'document'documentid' 下的特定文档。我不断得到一个“空”值,它出错了:

   try {
      final user = await _auth.currentUser();
      if (user != null) {
        _loggedInUser = user;
        _userUid = _loggedInUser.uid;
        setState(() {
          // showSpinner = false;
          print(_userUid);
        });
      }
    } catch (e) {
      print(e);
    }
  }

  void getItemDetail() async {
    await _firestore
        .collection('users')
        .document(_userUid)
        .collection('items')
        .document(documentID)
        .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'];

      setState(() {
        dateCreated =
            new DateFormat.yMMMMd("en_US").format(createDate.toDate());
        itemDetails = snapshot.data;
        showSpinner = false;
        stockCheck();
        editDateCheck();
      });
    });
  }
 @override
  void initState() {
    testApp();
    getCurrentUser();
    getItemDetail();
    //   editDateCheck();
    super.initState();
  }
flutter error output:
[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
Receiver: null
Tried calling: []("item_name")
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1      DocumentSnapshot.[] (package:cloud_firestore/src/document_snapshot.dart:29:42)
#2      _ItemDetailScreenState.getItemDetail.<anonymous closure> (package:simmanager/screens/item_detail_screen.dart:77:26)
#3      _rootRunUnary (dart:async/zone.dart:1132:38)
#4      _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#5      _FutureListener.handleValue (dart:async/future_impl.dart:137:18)
#6      Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:678:45)
#7      Future._propagateToListeners (dart:async/future_impl.dart:707:32)
#8      Future._completeWithValue (dart:async/future_impl.dart:522:5)
#9      _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:30:15)
#10     _completeOnAsyncReturn (dart:async-patch/async_patch.dart:288:13)
#<…&gt;

documentid 是从上一页的导航器传递过来的。我已经打印了 (userid, documentid" 所有值都正确打印。

标签: firebaseflutterdartgoogle-cloud-firestore

解决方案


您应该始终检查您的快照是否有任何数据或 null 之类的,

if(snapshot!=null)

然后你总是应该检查快照内的数据是否为空,

if(snapshot.data!=null)

此外,在您的情况下,您称您是空对象上的数据。

我认为您需要将所有项目的snapshot['item_name']替换为snapshot.data['item_name']

您错误地调用了导致问题的 snapshot["your_field"] 而不是 snapshot.data["your_field"] 。

此外,始终建议在解析来自网络的数据时检查 null 安全性。


推荐阅读