使变量成为 Map 中的键

st_*_*rke 3 dart

我有两节课

  class Phone extends Observable
  {
     @observable String type = '';
     @observable String provider = '';
     @observable String num = '';

     Map<String, Map<String, String> map = {};

     Phone() {}
     Phone.build({ this.type,
                   this.provider,
                   this.num });
  }
Run Code Online (Sandbox Code Playgroud)

我尝试使用字段值作为地图中的键,如下所示

   Phone phone = new Phone();
   phone.map[phone.type] = {'type':'cell', 'provider':'Verizon', 'num':'1234567'};
Run Code Online (Sandbox Code Playgroud)

但它不起作用。如何使字段值成为地图的键?

Gün*_*uer 5

只需删除引号

phone.map[phone.type] = {type:'cell', provider:'Verizon', num:'1234567'};
Run Code Online (Sandbox Code Playgroud)

因为您在示例中使用字符串,所以这可能不适用,但请注意,如果您使用自定义类型的实例作为 Map 键...

The keys of a `HashMap` must have consistent [Object.operator==]
and [Object.hashCode] implementations. This means that the `==` operator
must define a stable equivalence relation on the keys (reflexive,
anti-symmetric, transitive, and consistent over time), and that `hashCode`
must be the same for objects that are considered equal by `==`.
Run Code Online (Sandbox Code Playgroud)