【问题标题】:Error: Class 'QuerySnapshot' has no instance getter 'data'错误:“QuerySnapshot”类没有实例获取器“数据”
【发布时间】:2020-09-24 21:55:57
【问题描述】:

我正在尝试创建一个包含 3 个选项卡的 UI 屏幕。最近项目、评论项目和个人资料。但是,recentitem 小部件中存在一些后端问题。显示错误:“QuerySnapshot”类没有实例获取器“数据”。 Ps:整个代码非常大,因此我分享了整个代码的文档:https://docs.google.com/document/d/1qs4ajPJ0DBjserBJ3iBZmPXPz1zTP7tIYSh8vceVQn8/edit?usp=sharing 最近项目():

Widget RecentItems() {
    return Padding(
      padding: const EdgeInsets.all(10.0),
      child: StreamBuilder(
          stream: Firestore.instance
              .collection("users")
              .document(uid)
              .collection("recent")
              .snapshots(),
          builder: (context, snapshot) {
            print(snapshot.data);
            List orders = List.from(Map.from(snapshot.data.data)['orders']);
            Map order;
            for (int i = 0; i < orders.length; i++) {
              if (orders[i]['orderId'] == widget.map['orderId'] &&
                  orders[i]['homemaker'] == widget.map['homemaker']) {
                order = orders[i];
                break;
              }
            }
            if (snapshot.data.isEmpty) {
              return Center(
                  child:
                  Text("OOPS, Looks like no one is serving!"));
            }
            print(order);
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(child: CircularProgressIndicator());
            } else if (snapshot.hasData) {
              print(snapshot.data.documents[0].data);
              return Container(
                height: 400,
                child: ListView.builder(
                    itemCount: snapshot.data.documents.length,
                    itemBuilder: (BuildContext context, int index) {
                      return Container(
                        margin: EdgeInsets.all(10.0),
                        width: MediaQuery
                            .of(context)
                            .size
                            .width,
                        height: 85,
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(10.0),),
                        child: Padding(
                          padding: const EdgeInsets.all(10.0),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Row(
                                children: <Widget>[
                                  Expanded(child: Text(
                                    "${snapshot.data.documents[index]
                                        .data["dishname"]}", style: TextStyle(
                                      fontSize: 15,
                                      fontWeight: FontWeight.bold),)),
                                  //Icon: how to access if food is veg or not
                                ],
                              ),
                              // SizedBox(height:5),
                              Row(
                                children: <Widget>[
                                  Expanded(child: Text(
                                    "${snapshot.data.documents[index]
                                        .data["homemaker"]}",
                                    style: TextStyle(fontSize: 10),)),
                                  Text("${snapshot.data.documents[index]
                                      .data["rating"]}",
                                      style: TextStyle(fontSize: 15)),
                                  Icon(
                                    Icons.star, color: Colors.yellow.shade800,
                                    size: 20,)
                                ],
                              ),
                              SizedBox(height: 5),
                              //How to access order date
                              Text(
                                "Ordered ${DateTime
                                    .parse(order['order_placed_at']
                                    .toDate()
                                    .toString())
                                    .day}/${DateTime
                                    .parse(order['order_placed_at']
                                    .toDate()
                                    .toString())
                                    .month}/${DateTime
                                    .parse(order['order_placed_at']
                                    .toDate()
                                    .toString())
                                    .year}}",
                                style: TextStyle(fontSize: 15.0,
                                    fontWeight: FontWeight.bold),
                              ),
                            ],
                          ),
                        ),
                      );
                    }),
              );
            } //
          }),
    );
  }

错误信息是:

The getter 'data' was called on null.
Receiver: null
Tried calling: data
The relevant error-causing widget was: 
  StreamBuilder<QuerySnapshot> file:///C:/Flutter/Naniz_eats/lib/UserProfilePage.dart:434:14
════════════════════════════════════════════════════════════════════════════════════════════════════
I/flutter (28940): Instance of 'QuerySnapshot'

════════ (3) Exception caught by widgets library ═══════════════════════════════════════════════════
Class 'QuerySnapshot' has no instance getter 'data'.
Receiver: Instance of 'QuerySnapshot'
Tried calling: data
The relevant error-causing widget was: 
  StreamBuilder<QuerySnapshot> file:///C:/Flutter/Naniz_eats/lib/UserProfilePage.dart:434:14

【问题讨论】:

    标签: flutter dart flutter-layout flutter-dependencies dart-pub


    【解决方案1】:

    有几件事或全部可能导致这种情况:

    1. builder 第一行中的print。如果snapshot 确实为空,那么您已经在调用数据而不首先检查它是否为空。

    2. snapshot.data.data 我认为是builder 第二行的错字

    3. 事实上,您在没有先检查snapshot.hasDatasnapshot.data.documents.length != 0 的情况下对快照执行操作,以确保您没有对空快照执行操作。

    您还应该能够通过按下错误消息来具体检查导致错误的行,其中一条错误消息应包含指向特定行的链接(未在您的问题中显示,应该位于长一堆错误信息)

    【讨论】:

    • 错误消息指向的行是 child: StreamBuilder(
    【解决方案2】:

    这段代码:

    Firestore.instance
                  .collection("users")
                  .document(uid)
                  .collection("recent")
                  .snapshots()
    

    返回一个QuerySnapshot类型的Stream,问题就在这里:

                List orders = List.from(Map.from(snapshot.data.data)['orders']);
    

    代码snapshot.data 将返回QuerySnapshot 的实例,而QuerySnapshot 不包含名为data 的实例变量。所以,如果你想要一个文档列表,那么你必须执行以下操作:

    List<DocumentSnapshot> orders = snapshot.data.documents;
    

    https://github.com/FirebaseExtended/flutterfire/blob/master/packages/cloud_firestore/cloud_firestore/lib/src/query_snapshot.dart#L17

    【讨论】:

    • 我应该用您提供的解决方案替换列表订单行
    • 我不确定您要达到的目标,但documents 将返回集合中的文档列表,因此请替换它
    • 我正在尝试从列表中的 firebase 获取数据,并将获取该数据以显示 UI 屏幕。好吧,我刚刚得到了代码,我只需要构建 UI,但我不能导致 firebase 问题..我尝试替换但错误仍然存​​在:错误:无法分配“DocumentSnapshot”类型的值到“地图”类型的变量
    • 有解决办法吗?
    • 可能是因为这个order = orders[i];注释for循环并再次运行它只是为了测试......你必须调试你的代码来解决问题..
    猜你喜欢
    • 2020-10-21
    • 2021-04-27
    • 1970-01-01
    • 2021-03-01
    • 1970-01-01
    • 2020-04-11
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多