在 nullsafety 之后使用带有 json_serializable 的 firestore

Posted

技术标签:

【中文标题】在 nullsafety 之后使用带有 json_serializable 的 firestore【英文标题】:Using firestore with json_serializable after nullsafety 【发布时间】:2021-06-20 16:12:00 【问题描述】:

我正在使用 json_serializable 和 firestore。 json_serializable 创建一个以 Map 作为参数的工厂方法,但在 nullsafety 更改后,firestore 开始返回 Map?作为文档数据,现在我无法调用 json_serializable 工厂来映射我的 Firestore 类型,因为显示此错误消息:The argument type 'Map<String, dynamic>?' can't be assigned to the parameter type 'Map<String, dynamic>'

有人可以帮我解决这个问题吗?我不能再将 json_serializable 与 firestore 一起使用吗?

我写了这个例子:

class Entity 
  const Entity(required this.id);

  final String id;

  factory Entity.fromJson(Map<String, dynamic> json) => _$EntityFromJson(json);
  Map<String, dynamic> toJson() => _$EntityToJson(this);


class Repository 
  Stream<List<Entity>> list() 
    return FirebaseFirestore.instance.collection('entity').snapshots().map((event) 
      return event.docs.map((e) 
        return Entity.fromJson(
          e.data() // The argument type 'Map<String, dynamic>?' can't be assigned to the parameter type 'Map<String, dynamic>'
        );
      ).toList();
    );
  

【问题讨论】:

查询的结果可以为空,并且您正在尝试分配一个非空变量,您可以让您的变量接受空并稍后处理,或者在分配给之前检查结果是否为空对象。 【参考方案1】:

我不知道这是正确的方法,但我使用 'as' 关键字将类型从 Object 转换为 MapImage example

doc.data() as Map<String, dynamic>

【讨论】:

请注意,获取不存在的文档时会失败。

以上是关于在 nullsafety 之后使用带有 json_serializable 的 firestore的主要内容,如果未能解决你的问题,请参考以下文章