将新项目写入firebase时出现错误状态

将新项目写入firebase时出现错误状态,firebase,flutter,google-cloud-firestore,Firebase,Flutter,Google Cloud Firestore,每当我尝试写一个新项目时,我都会遇到以下错误 错误状态:无法在DocumentSnapshot平台上获取字段 不存在 该函数仅在添加第一个项目时起作用,当我尝试添加具有相同“restaurantId”的新项目时,会出现错误。我不明白为什么这只是第一次增加。 另外,如果可能,请帮助我优化代码 void addItemCart(String restaurantId, String restItemId, double price, int quantity) async { L

每当我尝试写一个新项目时,我都会遇到以下错误

错误状态:无法在DocumentSnapshot平台上获取字段 不存在

该函数仅在添加第一个项目时起作用,当我尝试添加具有相同“restaurantId”的新项目时,会出现错误。我不明白为什么这只是第一次增加。 另外,如果可能,请帮助我优化代码

void addItemCart(String restaurantId, String restItemId, double price,
      int quantity) async {
    List<CartItem> cartItems = [];
    final String authId = FirebaseAuth.instance.currentUser.uid;
    Map<String, dynamic> restData;
    final newRest = await FirebaseFirestore.instance
        .collection('restaurants')
        .doc(restaurantId)
        .collection('restaurantItems')
        .doc(restItemId)
        .get()
        .then((value) => restData = value.data());

    int restQuantity = restData['quantity'];
    String restIdName = restData['name'];

    try {
      if (authId != null) {
        final cart = await FirebaseFirestore.instance
            .collection('users')
            .doc(authId)
            .collection('cart')
            .doc(authId)
            .get();

        if (!cart.exists) {
          await FirebaseFirestore.instance
              .collection('users')
              .doc(authId)
              .collection('cart')
              .doc(authId)
              .set({'restaurantId': restaurantId});

          await FirebaseFirestore.instance
              .collection('users')
              .doc(authId)
              .collection('cart')
              .doc(authId)
              .collection('restItemId')
              .doc(restItemId)
              .set(
            {'price': price * quantity, 'quantity': 1, 'name': restIdName},
          );
          _items.add(
            CartItem(
                id: restItemId,
                title: restIdName,
                price: price,
                quantity: quantity,
                restaurantId: restaurantId),
          );
        } else if (cart.data()['restaurantId'] == restaurantId) {
          print('$restIdName in If loop');
          print('$quantity in If loop');
          // print('$quantity in If loop');
          try {
            await FirebaseFirestore.instance
                .collection('users')
                .doc(authId)
                .collection('cart')
                .doc(authId)
                .collection('restItemId')
                .doc(restItemId)
                .get()
                .then(
              (value) async {
                print('${value['quantity']} value');
                if (value['quantity'] <= restQuantity) {
                  await FirebaseFirestore.instance
                      .collection('users')
                      .doc(authId)
                      .collection('cart')
                      .doc(authId)
                      .collection('restItemId')
                      .doc(restItemId)
                      .set({
                    'name': value.data()['name'],
                    'quantity': value.data()['quantity'] == null
                        ? 0
                        : value.data()['quantity'] + 1,
                    'price': price * (value.data()['quantity'] + 1)
                  });
                  _items.add(
                    CartItem(
                        id: restItemId,
                        title: restIdName,
                        price: price,
                        quantity: quantity,
                        restaurantId: restaurantId),
                  );
                }
              },
            );
          } catch (error) {
            print(error);
          }
        } else {
          print('alert! new rest');
          // Return an alert to change the restauran name to the user
        }
      }
    } catch (error) {
      print(error);
    }
  }
void addItemCart(String restaurantId、String restItemId、双倍价格、,
int数量)异步{
列表项=[];
最后一个字符串authId=FirebaseAuth.instance.currentUser.uid;
地图数据;
final newRest=等待FirebaseFirestore.instance
.收藏(‘餐厅’)
博士(餐厅)
.collection(“restaurantItems”)
.doc(restItemId)
.get()
.然后((value)=>restData=value.data());
int restQuantity=restData['quantity'];
字符串restIdName=restData['name'];
试一试{
如果(authId!=null){
最终购物车=等待FirebaseFirestore.instance
.collection('用户')
.doc(authId)
.collection('购物车')
.doc(authId)
.get();
如果(!cart.exists){
等待FirebaseFirestore.instance
.collection('用户')
.doc(authId)
.collection('购物车')
.doc(authId)
.set({'restaurantId':restaurantId});
等待FirebaseFirestore.instance
.collection('用户')
.doc(authId)
.collection('购物车')
.doc(authId)
.collection('restItemId')
.doc(restItemId)
.设置(
{'price':价格*数量,'quantity':1,'name':restIdName},
);
_items.add(
卡蒂姆(
id:restItemId,
标题:restIdName,
价格:价格,
数量:数量,,
餐厅(restaurantId):餐厅(restaurantId),
);
}else if(cart.data()['restaurantId']==restaurantId){
打印('If循环中的$restIdName');
打印(“$quantity in If loop”);
//打印(“$quantity in If loop”);
试一试{
等待FirebaseFirestore.instance
.collection('用户')
.doc(authId)
.collection('购物车')
.doc(authId)
.collection('restItemId')
.doc(restItemId)
.get()
.那么(
(值)异步{
打印(“${value['quantity']}value”);

如果(value['quantity']错误告诉我们两件事:

1-它位于一个
get()
查询中。您只有三个查询,因此我们可以消除其他firestore函数

2-它表示您正试图从一个不存在的文档中检索数据

我相信这一点,如果你的代码的第二部分:

await FirebaseFirestore.instance
.collection('users')
.doc(authId)
.collection('cart')
.doc(authId)
.collection('restItemId')
.doc(restItemId)
.get()
  • 确保
    .doc(restItemId)
    存在。 仔细检查您是否通过了
    .doc()
    IDs存在。您在创建\设置文档时不会遇到任何问题,因为Firebase将以您指定的结构为您创建文档,即使它们不存在。但它不会获取任何不存在的内容,并将抛出您看到的错误。代码的第一部分工作,因为文档还不存在d您创建了它们,第二部分您要求firebase提供一个文档,您认为该文档是创建的,但不是,或者可能是使用您认为您指定的ID创建的,但没有

  • 在监视Firebase控制台的同时运行您的函数,查看文档和子集合是如何创建的,记下ID,并跟踪它。我建议打破用于创建条目的逻辑,因为正如您可能看到的那样,即使它的格式很好,它也会变得非常复杂

  • 创建新条目的逻辑总是相同的,因此将函数分为几个部分,一个检查是否存在某些内容的部分,一个简单的if statemnet,您可以使用,并根据条件将它们发送到两个函数,即
    void addNewRestaurant()
    void existingRestaurant()

作废addItemCart(字符串restaurantId、字符串restItemId、双倍价格、,
int数量)异步{
列表项=[];
最后一个字符串authId=FirebaseAuth.instance.currentUser.uid;
地图数据;
final newRest=等待FirebaseFirestore.instance
.收藏(‘餐厅’)
博士(餐厅)
.collection(“restaurantItems”)
.doc(restItemId)
.get()
.然后((value)=>restData=value.data());
int restQuantity=restData['quantity'];
字符串restIdName=restData['name'];
试一试{
如果(authId!=null){
最终购物车=等待FirebaseFirestore.instance
.collection('用户')
.doc(authId)
.collection('购物车')
.doc(authId)
.get();
最终值=等待FirebaseFirestore.instance
.collection('用户')
.doc(authId)
.collection('购物车')
.doc(authId)
.collection('restItemId')
.doc(restItemId)
.get();
//if(restItem.exists)
打印(“${value.data()}:餐厅项目数据”);
如果(!cart.exists){
等待FirebaseFirestore.instance
.collection('用户')
.doc(authId)
.collection('购物车')
.doc(authId)
.set({'restaurantId':restaurantId});
等待FirebaseFirestore.instance
.collection('用户')
.doc(authId)
.collection('购物车')
.doc(authId)
.collection('restItemId')
.doc(restItemId)
.设置(
void addItemCart(String restaurantId, String restItemId, double price,
      int quantity) async {
    List<CartItem> cartItems = [];
    final String authId = FirebaseAuth.instance.currentUser.uid;
    Map<String, dynamic> restData;
    final newRest = await FirebaseFirestore.instance
        .collection('restaurants')
        .doc(restaurantId)
        .collection('restaurantItems')
        .doc(restItemId)
        .get()
        .then((value) => restData = value.data());

    int restQuantity = restData['quantity'];
    String restIdName = restData['name'];

    try {
      if (authId != null) {
        final cart = await FirebaseFirestore.instance
            .collection('users')
            .doc(authId)
            .collection('cart')
            .doc(authId)
            .get();

        final value = await FirebaseFirestore.instance
            .collection('users')
            .doc(authId)
            .collection('cart')
            .doc(authId)
            .collection('restItemId')
            .doc(restItemId)
            .get();

        // if(restItem.exists)
        print('${value.data()}: restaurant item data');

        if (!cart.exists) {
          await FirebaseFirestore.instance
              .collection('users')
              .doc(authId)
              .collection('cart')
              .doc(authId)
              .set({'restaurantId': restaurantId});

          await FirebaseFirestore.instance
              .collection('users')
              .doc(authId)
              .collection('cart')
              .doc(authId)
              .collection('restItemId')
              .doc(restItemId)
              .set(
            {'price': price * quantity, 'quantity': 1, 'name': restIdName},
          );
          _items.add(
            CartItem(
                id: restItemId,
                title: restIdName,
                price: price,
                quantity: quantity,
                restaurantId: restaurantId),
          );
        } else if (cart.data()['restaurantId'] == restaurantId) {
          print('$restIdName in If loop');
          print('$quantity in If loop');
          // print('$quantity in If loop');
          try {
        
            if (!value.exists) {
              print('$restIdName does not exist');
              await FirebaseFirestore.instance
                  .collection('users')
                  .doc(authId)
                  .collection('cart')
                  .doc(authId)
                  .collection('restItemId')
                  .doc(restItemId)
                  .set(
                {'name': restIdName, 'quantity': 1, 'price': price},
              );
            } else if (value['quantity'] < restQuantity) {
              await FirebaseFirestore.instance
                  .collection('users')
                  .doc(authId)
                  .collection('cart')
                  .doc(authId)
                  .collection('restItemId')
                  .doc(restItemId)
                  .set(
                {
                  'name': value.data()['name'],
                  'quantity': value.data()['quantity'] == null
                      ? 0
                      : value.data()['quantity'] + 1,
                  'price': price * (value.data()['quantity'] + 1)
                },
              );
              _items.add(
                CartItem(
                    id: restItemId,
                    title: restIdName,
                    price: price,
                    quantity: quantity,
                    restaurantId: restaurantId),
              );
            }
          } catch (error) {
            print(error);
          }
        } else {
          print('alert! new rest');
          // Return an alert to change the restauran name to the user
        }
      }
    } catch (error) {
      print(error);
    }
  }