我正在尝试查询嵌套在集合'users / document'useruid'/ collection'items'/'document'documentid'下的特定文档。我一直得到一个'null'值,并且出错了
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)
#<…>
文档ID是从上一页的导航器传递的。我已经正确打印了(userid,documentid“所有值。
答案 0 :(得分:0)
您应始终检查快照是否有任何数据或类似null的数据,
if(snapshot!=null)
然后,您应该始终检查快照中的数据是否为空或不一样,
if(snapshot.data!=null)
另外,在您的情况下,您正在调用的是空对象上的数据。
我认为您需要将 snapshot ['item_name'] 替换为 snapshot.data ['item_name'] 。
您错误地调用了快照[“ your_field”]而不是快照.data [“您的域”],这是导致问题的原因。
此外,始终建议在解析来自网络的数据时检查null安全性。