我很困惑为什么以下Dart代码会生成运行时错误:

class Store<ID, T> {
  Store({Map<ID, T> values = const {}}) : _cache = values;

  final Map<ID, T> _cache;

  void put(ID id, T value) {
    _cache[id] = value;
  }
}

...
final foo = Store<int, Store<int, String>>();

// Runtime error inside `Store.put`:
// TypeError: 7: type 'int' is not a subtype of type 'Never'
foo.put(7, Store<int, String>());

如果我直接像这样使用Map,这不是问题:

final foo = Map<int, Map<int, String>>();
foo[7] = Map<int, String>());

要让Store个发挥作用,我需要了解有关Dart仿制药的某些内容吗?

推荐答案

如果您在编辑器中将鼠标悬停在const {}以上,它应该显示Type: Map<Never, Never>.无论如何,您不能在这里使用const map ,因为您无法变异const map .您可以在初始化器列表中为_cache分配一个非常数映射.

class Store<ID, T> {
  Store({Map<ID, T>? values}) : _cache = values ?? {};

  final Map<ID, T> _cache;

  void put(ID id, T value) {
    _cache[id] = value;
  }
}

Dart相关问答推荐

对字母数字字符串数组进行排序

如何获取包含在 Dart 包中的assets资源 的文件路径?

将所有内容放在有序组中,但将括号中的字符组合在一起

Dart/Flutter ffi(外部函数接口)本机回调,例如:sqlite3_exec

无法在 IOS 上使用 firebase 运行Flutter应用程序

Flutter pod 安装问题 - # 的未定义方法 `each_child'

什么时候在 Dart 中使用interfaces接口?

NoSuchMethodError:在 null 上调用了方法validate

不要将 PageView 居中 - Flutter

Flutter web url 导航

属性 'docs' 不能无条件访问,因为接收到的可能是 'null' Flutter

如何在flatter中使用SQFlite更新数据库表

'dart:async' 的函数 `runZoned` 的用途

Dart 中的构造函数和初始化列表有什么区别?

如何在dart列表中找到一个元素

为什么不推荐使用 context2d.backingStorePixelRatio?

~ 在 Dart 中是什么意思?

Cancel stream onData

pub 依赖和 dev_dependencies 有什么区别?

如何使异步 Dart 调用同步?