【问题标题】:Map<String, dynamic> for FireStore ErrorsFireStore 错误的 Map<String, dynamic>
【发布时间】:2018-10-24 20:07:51
【问题描述】:

尝试为 FireStore 中的项目创建地图,如下所示:

class Hero {
  final int id;
  String name;
  bool pickupNeeded;
  String url;
  bool partPickup;


  Hero(this.id, this.name, this.pickupNeeded, this.url, this.partPickup);


  factory Hero.fromJson(Map<String, dynamic> hero) =>
      Hero(_toInt(hero['id']), hero['name'], hero['pickupNeeded'], hero['url'], hero['partPickup']);

  Map toJson() => {'id' : id, 'name': name, 'pickupNeeded' : pickupNeeded, 'url' : url, 'partPickup' : partPickup,};

  int _toInt(id) => id is int ? id : int.parse(id);

但是,_toInt in the hero(_toInt(hero['id']... 给出错误:“无法从工厂构造函数访问实例成员”

我错过了什么? AngularDart Tour of Heroes 在他们的GitHub sample 上是这样的。

hero_service 获取英雄召唤:

Future<Hero> get(dynamic id) async {
    try {
      return Hero.fromJson(id);
    } catch (e) {
      throw _handleError(e);
    }
  }

以及调用它的 Hero 组件:

void onActivate(_, RouterState current) async {
    final id = RoutePaths().getId(current.parameters);
    if (id != null) hero = await (_heroService.get(id));
  }

【问题讨论】:

    标签: angular firebase dart google-cloud-firestore angular-dart


    【解决方案1】:

    _toInt 设为静态,你就是金子。

    static int _toInt(id) => id is int ? id : int.parse(id);
    

    【讨论】:

    • 也许不是。这消除了 Dart Analyzer 错误,但是当我尝试运行它时,我得到一个错误: Type 'int' is not a subtype of expected type 'Map' 无论我尝试将其更改为哪种类型,我得到一个类似的错误。
    • 类型“int”不是预期类型“Map”的子类型。异常:异常:服务器错误;原因:类型“int”不是预期类型“Map”的子类型。 STACKTRACE: dart:sdk_internal
    • 您是否尝试使用 int 值调用 Hero.fromJson(..)
    • 是的。我相信 RoutePaths 返回一个 int。我已经添加了拨打电话的项目。 HeroComponent 调用 HeroService。注意:当我将 int id 强制为 String 时,我得到了同样的错误。
    猜你喜欢
    • 2018-10-14
    • 2021-09-11
    • 2021-04-13
    • 2021-09-25
    • 2021-03-23
    • 2020-07-01
    • 2019-01-22
    • 2021-07-01
    • 2021-02-11
    相关资源
    最近更新 更多