【问题标题】:The argument type 'Object?' can't be assigned to the parameter type 'DocumentSnapshot'参数类型“对象?”不能分配给参数类型“DocumentSnapshot”
【发布时间】:2021-07-07 05:20:43
【问题描述】:

我刚刚更新到 Dart2 和 Flutter sdk: '>=2.12.0

return Scaffold(
  body: FutureBuilder(
    future: usersRef.doc(widget.accountiD).get(),
    builder: (context, snapshot) {
      if (!snapshot.hasData) {
        return buildLoading();
      }
      UserAccount currentUser = UserAccount.fromDocument(snapshot.data);
      return ListView(
        children: []
      );
    }
  ),
);

错误出现在 snapshot.data 上,说 参数类型“对象?”不能分配给参数类型“DocumentSnapshot”。 该怎么办?我需要帮助。

【问题讨论】:

  • 试试FutureBuilder<DocumentSnapshot>
  • 谢谢你

标签: firebase flutter google-cloud-firestore


【解决方案1】:

改成这样:

return Scaffold(
  body: FutureBuilder<DocumentSnapshot>(
    future: usersRef.doc(widget.accountiD).get(),
    builder: (context, snapshot) {
      if (!snapshot.hasData) {
        return buildLoading();
      }
      UserAccount currentUser = UserAccount.fromDocument(snapshot.data.data()); //you need to add "data()" to access the map of objects inside snapshot.data
      return ListView(
        children: []
      );
    }
  ),
);

【讨论】:

  • 嘿@Huthaifa 谢谢你,它成功了!但我不需要在我的 snapshot.data 上添加 .data()。因为在我的 UserAccount 屏幕上,我实际上已将所有字段设置为 .data() 例如 ``` factory UserAccount.fromDocument(DocumentSnapshot doc) { return UserAccount( id: doc.data()! ['id'], 电子邮件:doc.data()!['email'], ); } ``` 我对快照所做的唯一事情就是这个 snapshot.data! 我在末尾添加了 !。我能够得到我的数据。无论如何,感谢您提出的建议。谢谢你,保重!
  • 不客气!很高兴它成功了。 :)
【解决方案2】:

我前段时间遇到了同样的问题,但又遇到了,忘记了将我带到这里的解决方案。

我找到的解决方案是使用 "as" 关键字

示例

snapshot.data as int

snapshot.data as String

只需对任何其他数据类型执行相同操作即可。 希望能帮助到你。来自??的回复。

【讨论】:

    【解决方案3】:
    return Scaffold(
      body: FutureBuilder<DocumentSnapshot>(
        future: usersRef.doc(widget.accountiD).get(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return buildLoading();
          }
          UserAccount currentUser = UserAccount.fromDocument(snapshot.data!); //(Add after snapshot.data)
            return ListView(
              children: []
            );
        }
      ),
    );
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 2022-01-01
    • 2021-11-06
    • 2021-08-05
    • 1970-01-01
    • 2021-08-18
    • 2021-08-29
    • 2021-11-06
    • 1970-01-01
    相关资源
    最近更新 更多