【问题标题】:Using firestore with json_serializable after nullsafety在 nullsafety 之后使用带有 json_serializable 的 firestore
【发布时间】: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();
    });
  }
}

【问题讨论】:

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

标签: firebase flutter json-serializable


【解决方案1】:

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

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

【讨论】:

  • 请注意,获取不存在的文档时会失败。
猜你喜欢
  • 1970-01-01
  • 2021-06-05
  • 2019-10-21
  • 1970-01-01
  • 2021-10-26
  • 2017-08-19
  • 2018-08-15
  • 2021-06-21
  • 2020-01-18
相关资源
最近更新 更多