首页 > 解决方案 > Flutter firebase 查询快照错误:“未处理的异常:错误状态:无元素”

问题描述

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

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)] 未处理异常:错误状态:无元素

标签: firebaseflutterdartgoogle-cloud-firestore

解决方案


查询返回的 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.
      }
    });

推荐阅读