【问题标题】:The method 'data' isn't defined for the type 'Object'. Try correcting the name to the name of an existing method, or defining a method named 'data'没有为“对象”类型定义方法“数据”。尝试将名称更正为现有方法的名称,或定义名为“数据”的方法
【发布时间】:2021-09-16 15:40:30
【问题描述】:

我无法显示来自 Firebase 的数据。这是我在 FutureBuilder 中使用的代码。看起来data()有错误,但我不知道是哪一个,有人知道吗?

这就是我得到的:“方法‘数据’没有为‘对象’类型定义。 尝试将名称更正为现有方法的名称,或定义名为“数据”的方法。”

if(snapshot.connectionState == ConnectionState.done) {
  Map<String, dynamic> documentData = snapshot.data!.data() as Map<String, dynamic>;
     return ListView(
       children: [

         CustomSubtitle(
           text: "${documentData['01 - Brand']}"
         ),

         CustomTitle(
           text: "${documentData['02 - Name']}",
         ),

         CustomText(
          text: "${documentData['04 - Description']}",
         )

       ],
     );
   }

【问题讨论】:

  • ` Map documentData = snapshot.data as Map;`
  • 不客气。
  • 哎呀...我的代码现在还可以,但是当我运行应用程序时,出现错误“类型 '_JsonDocumentSnapshot' 不是类型 'Map 的子类型类型转换”。你有什么想法吗?
  • 是的,我重新阅读了您的代码几次并意识到您应该将 if 条件更改为 if(snapshot.hasData && !(snapshot.hasError)) {...}。我假设这个函数是 FutureBuilder 小部件中构建器的一部分。
  • 是的,谢谢,我找到了解决方案。感谢您的时间和帮助!

标签: firebase flutter


【解决方案1】:

您正在使用QuerySnapshot 的代码。对于这样一个你的代码可以工作,但考虑到你如何使用你收到的结果数据DocumentSnapshot。为此,只需将您的代码更改为:

if(snapshot.connectionState == ConnectionState.done) {
  Map<String, dynamic> documentData = snapshot.data as Map<String, dynamic>;
     return ListView(
       children: [

         CustomSubtitle(
           text: "${documentData['01 - Brand']}"
         ),

         CustomTitle(
           text: "${documentData['02 - Name']}",
         ),

         CustomText(
          text: "${documentData['04 - Description']}",
         )

       ],
     );
   }

【讨论】:

  • 谢谢!!实际上,当我删除数据后的 () 时它是有效的 :)
【解决方案2】:

如果有人在我的情况下,我已经找到了解决方案:

builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {

    if(snapshot.connectionState == ConnectionState.done) {
    DocumentSnapshot<Object?> documentData = snapshot.data!;
     return ListView(
       children: [

           CustomSubtitle(
             text: "${documentData['01 - Brand']}"
           ),

           CustomTitle(
             text: "${documentData['02 - Name']}",
           ),

           CustomText(
             text: "${documentData['04 - Description']}",
           )

         ],
       );
     }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-29
    • 2022-07-26
    • 1970-01-01
    • 2020-09-03
    • 2023-02-07
    • 2022-08-22
    • 1970-01-01
    • 2022-06-10
    相关资源
    最近更新 更多