Flutter firebase 查询快照错误:“未处理的异常:错误状态:无元素”

Posted

技术标签:

【中文标题】Flutter firebase 查询快照错误:“未处理的异常:错误状态:无元素”【英文标题】:Flutter firebase query snapshot error: "Unhandled Exception: Bad state: No element" 【发布时间】:2021-02-21 17:46:21 【问题描述】:

获取具有必填字段值的文档,但这不起作用

await FirebaseFirestore.instance
            .collection('orders')
            .where("id", isEqualTo: orderList[index].id)
            .get()
            .then((snapshot) 
          snapshot.docs.first.reference.update("status": 'Rejected');
          print("yes");
        );

但是这行得通

await FirebaseFirestore.instance
        .collection('orders')
        .where("id", isEqualTo: orderList[index].id)
        .get()
        .then((snapshot) 
      //snapshot.docs.first.reference.update("status": 'Rejected');
      print("yes");
    );

错误

E/flutter (10845): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] 未处理异常:错误状态:无元素

【问题讨论】:

【参考方案1】:

查询返回的 QuerySnapshot 对象可以返回 0 个或多个 DocumentSnapshot 对象。在索引到 docs 数组之前,您应该检查是否有超过 0 个。

await FirebaseFirestore.instance
    .collection('orders')
    .where("id", isEqualTo: orderList[index].id)
    .get()
    .then((snapshot) 
      if (snapshot.docs.length > 0) 
        snapshot.docs.first.reference.update("status": 'Rejected');
      
      else 
        // Figure out what you want to do if the list is empty.
        // This means your query matched no documents.
      
    );

【讨论】:

Cloud Firestore 中的值未更新 如果您有新问题,请发布一个新问题并说明哪些问题没有按照您的预期工作,以及您的调试信息。确保您正在记录所有内容并检查错误。

以上是关于Flutter firebase 查询快照错误:“未处理的异常:错误状态:无元素”的主要内容,如果未能解决你的问题,请参考以下文章