如何从Firebase Flutter获取fieldValue.arrayUnion数据

时间:2020-11-03 14:41:41

标签: firebase flutter dart google-cloud-firestore

我已经要求fieldunion数组的数据

Future _getData(String email) async {
        await FirebaseFirestore.instance
            .collection("shop")
            .get()
            .then((querySnapshot) {
          querySnapshot.docs.forEach((result) {
            print(result.data()["products"]);
          });
        });
      }

这是我得到的数据,它是产品的fieldunion数组。

[{img:[https://firebasestorage.googleapis.com/v0/b/geniemart-387b1.appspot.com/o/seller%2Fproduct%2Frohanchoudhary2000%40gmail.com%2F20%2Fimage_1?alt=media&token= 6b67a55d-01aa-4970-b518-719c30db7938,https://firebasestorage.googleapis.com/v0/b/geniemart-387b1.appspot.com/o/seller%2Fproduct%2Frohanchoudhary2000%40gmail.com%2F20%2Fimage_2?alt= media&token = 483b46e0-9d8f-48ec-b431-d083341d4815,https://firebasestorage.googleapis.com/v0/b/geniemart-387b1.appspot.com/o/seller%2Fproduct%2Frohanchoudhary2000%40gmail.com%2F20%2Fimage_3? alt = media&token = fea76365-59cd-47d2-96a4-55a9387dfbf5,https://firebasestorage.googleapis.com/v0/b/geniemart-387b1.appspot.com/o/seller%2Fproduct%2Frohanchoudhary2000%40gmail.com%2F20% 2Fimage_4?alt = media&token = a2136333-d099-4465-8121-2cf9f2e75d61],mprice:123,频率:[],折扣:12,销售商:制造商,长:72.0,寿命:5年,制造商:制造商,isveg:是,oprice:123,name:tgbbb,id:10000000,category:Tomato,品牌:tgbbb,lat:28.0,d esc:gyyhhh}

现在,我要具体获取其类别之一的属性的值。怎么做? result.data()["products"][2]["category"]无法正常工作。

[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: RangeError (index): Invalid value: Not in inclusive range 0..1: 2

1 个答案:

答案 0 :(得分:2)

如果不使用jsonDecode方法将其转换为List,请确保执行result.data()[“ products”]时返回的数据为List类型。 为了让您能够访问该列表的字段

现在确定以上内容之后

因此,如果它是字符串,请尝试以下操作:

dynamic results = jsonDecode(result.data()[“ products”])); 字符串category = results [0] [“ category”];

如果直接已经是列表,则可以这样访问类别字段: result.data()[“产品”] [0] [“类别”]