参数类型“对象?” 无法分配给参数类型“DocumentSnapshot”

Ade*_*Jr. 1 firebase flutter google-cloud-firestore

我刚刚更新到 Dart2 和 Flutter sdk: '>=2.12.0 <3.0.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: []
      );
    }
  ),
);
Run Code Online (Sandbox Code Playgroud)

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

Hut*_*yad 5

改成这样:

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: []
      );
    }
  ),
);
Run Code Online (Sandbox Code Playgroud)

  • 嘿@Huthaifa 谢谢你,它成功了!但我不需要在我的 snapshot.data 上添加 **.data()** 。因为在我的 UserAccount 屏幕上,我实际上已将所有字段设置为 **.data()** 例如```factory UserAccount.fromDocument(DocumentSnapshot doc) { return UserAccount( id: doc.data()!['id '], 电子邮件: doc.data()!['电子邮件'], ); } ``` 我对快照所做的唯一一件事就是这个 **snapshot.data!** 我在最后添加了 **!**。我能够获取我的数据。不管怎样,谢谢你的建议,它有效。谢谢你并保重! (2认同)

New*_*oPi 5

不久前我遇到了同样的问题,然后又遇到了这个问题,并且忘记了将我带到这里的解决方案。

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

例子

snapshot.data as int
Run Code Online (Sandbox Code Playgroud)

或者

snapshot.data as String
Run Code Online (Sandbox Code Playgroud)

对任何其他数据类型执行相同的操作。希望能帮助到你。答复由 发送。