【问题标题】:Why is snapshot.data.length deprecated?为什么不推荐使用 snapshot.data.length?
【发布时间】:2021-10-12 23:38:09
【问题描述】:

我正在使用 firebase_auth 3.0.1、firebase_core 1.4.0、cloud_firestore 2.4.0。 当我尝试从 firestore 获取数据时, data.length 和 data[index].get("name") 不断被弃用。请帮忙。

Future getMenus() async{
    var firestore = FirebaseFirestore.instance;
    QuerySnapshot qn = await firestore.collection("products").get();

    return qn.docs;
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<DocumentSnapshot>>(
      future: getMenus(),
      builder: (context, snapshot) {
        if(snapshot.hasData){
          print("ye");
          return ListView.builder(
            itemCount: snapshot.data.length,
            itemBuilder: (_, index){
              return ListTile(
                title: Text(snapshot.data[index].data["name"])
              );
            }
          );
            // CustomText(text: "data", size: 20, colors: black, weight: FontWeight.bold);

        }
        else if(snapshot.connectionState == ConnectionState.waiting){
          return Center(
            child: Text("Loading...")
          );
        }
        else{
          print("no");
          return CustomText(text: "No", size: 20, colors: black, weight: FontWeight.bold);

        }
      },
    );
  }

【问题讨论】:

  • 你得到什么错误信息?

标签: firebase flutter dart google-cloud-firestore


【解决方案1】:

您的snapshot.dataList&lt;QueryDocumentSnapshot&gt;。 要访问文档的数据,您可以这样做:

final docs = snapshot.data;

final data = snapshot.data.elementAt(index).data();

print(
  data['name'],
);

【讨论】:

  • data[index] 已弃用
  • 使用 .elementAt 如帖子所示。 (我编辑过)
猜你喜欢
  • 2016-02-23
  • 2017-11-04
  • 2011-10-22
  • 2011-04-11
  • 2012-12-07
  • 2012-05-16
  • 2020-06-29
  • 2014-08-11
  • 2016-06-19
相关资源
最近更新 更多