【问题标题】:I have error flutter null safety migration我有错误颤动空安全迁移
【发布时间】:2021-11-02 00:54:28
【问题描述】:

我正在将我在 sdk 2.7 中编写的 Flutter Firebase 代码迁移到 null 安全版本,但出现了问题。 firebase 用户模型代码中的 snapshot.data() 存在问题。

  UserModel.fromMap(Map<String, dynamic> map, this.userKey, {this.reference})
      : profileImg = map[KEY_PROFILEIMG],
        username = map[KEY_USERNAME],
        email = map[KEY_EMAIL],
        likedPosts = map[KEY_LIKEDPOSTS],
        followers = map[KEY_FOLLOWERS],
        followings = map[KEY_FOLLOWINGS],
        myPosts = map[KEY_MYPOSTS];

  UserModel.fromSnapShot(DocumentSnapshot snapshot)
      : this.fromMap(snapshot.data(), snapshot.id, //snapshot.data() error
            reference: snapshot.reference);

enter image description here

snapshot.data() 错误

The argument type 'Object?' can't be assigned to the parameter type 'Map<String, dynamic>'.

我可以知道这个问题吗? 谢谢。

【问题讨论】:

    标签: firebase flutter


    【解决方案1】:

    我建议你先深入了解一下 null-safty,一开始它会让人困惑,但很快你就会很容易理解它。
    然而,长话短说,null-safty 意味着变量不能为空,除非你用 '?' 指定它。在类型之后
    在您的代码中,您指定了fromMap 的第一个参数,即map,它不能为null,因为您没有添加'?',而snapshot.data() 可能返回null。

    要修复它:

    • 使用 ? 使地图可以为空?要像 -> Map&lt;String, dynamic&gt;? map 这不好,因为它来自Map 函数。
    • 检查snapshot.data() 的值是否为空:
      • 请勿拨打fromMap
      • 或者传递一个替代值,比如空对象{}

    【讨论】:

      猜你喜欢
      • 2021-07-27
      • 2021-08-07
      • 1970-01-01
      • 2021-04-17
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-28
      相关资源
      最近更新 更多