Flutter获取Firebase Firestore文档ID报错:Cannot read properties of undefined (reading 'id')
问题分析与解决方法
你的问题出在混用了await和.then()/.catchError(),导致docRef没有拿到Firestore返回的DocumentReference对象,而是.then()回调的返回值(大概率是void),自然无法访问id属性。
错误原因拆解
当你使用await时,会等待add()方法返回的Future完成,但你紧接着链式调用了.then(),此时await实际接收的是.then()执行后的结果——而successAlert(context)应该是没有返回值的,所以docRef最终是undefined,调用docRef.id就会触发报错。
修正方案
方案一:仅使用await+try-catch(推荐,代码更易读)
try { DocumentReference docRef = await FirebaseFirestore.instance .collection('blogs') .add({ 'title': titleController.text, 'body': myController.text, 'author': name, 'date': DateFormat('dd/MM/yyyy,hh:mm').format(DateTime.now()), }); // 此时docRef是正确的DocumentReference,可正常访问id print(docRef.id); successAlert(context); } catch (error) { errorAlert(context); } titleController.clear(); myController.clear();
方案二:仅使用.then()/.catchError()
如果坚持用链式调用,不要加await,并在.then()的回调里处理文档ID和成功提示:
FirebaseFirestore.instance .collection('blogs') .add({ 'title': titleController.text, 'body': myController.text, 'author': name, 'date': DateFormat('dd/MM/yyyy,hh:mm').format(DateTime.now()), }) .then((docRef) { // 这里的docRef是add()返回的DocumentReference print(docRef.id); successAlert(context); }) .catchError((error) => errorAlert(context)); titleController.clear(); myController.clear();
内容的提问来源于stack exchange,提问作者Devika
相关产品推荐
相关产品推荐

