Dart 将 Map 添加到动态时出错。正确吗?

问题描述 投票:0回答:1
void main() {
  dynamic a = {'a' : 'a', 'b' : 'b', 'c':'c'};
  a['d'] = {'dd':'dd'};
}

DartPad 捕获未处理TypeError:TypeError:实例 'IdentityMap':类型 'IdentityMap' 是 不是“String”类型的子类型 https://storage.googleapis.com/nnbd_artifacts/3.6.0/dart_sdk.js 4484:11 对象.抛出 https://storage.googleapis.com/nnbd_artifacts/3.6.0/dart_sdk.js 15812:15 对象._failedAsCheck https://storage.googleapis.com/nnbd_artifacts/3.6.0/dart_sdk.js 15798:14 dart_rti.Rti.new._generalAsCheckImplementation https://storage.googleapis.com/nnbd_artifacts/3.6.0/dart_sdk.js 30307:63 _js_helper.IdentityMap.from._set https://storage.googleapis.com/nnbd_artifacts/3.6.0/dart_sdk.js 4722:16 对象._checkAndCall https://storage.googleapis.com/nnbd_artifacts/3.6.0/dart_sdk.js 4774:17 对象.callMethod https://storage.googleapis.com/nnbd_artifacts/3.6.0/dart_sdk.js 4777:17 对象.dsend blob:null/bf8ecf44-b93c-4548-ac5e-c180547a1b46 224:10 主要$0 斑点:空/bf8ecf44-b93c-4548-ac5e-c180547a1b46 259:18
https://storage.googleapis.com/nnbd_artifacts/3.6.0/dart_sdk.js 43377:14 _rootRun https://storage.googleapis.com/nnbd_artifacts/3.6.0/dart_sdk.js 42207:14 async._CustomZone.new.run https://storage.googleapis.com/nnbd_artifacts/3.6.0/dart_sdk.js 43521:92 对象._runZoned https://storage.googleapis.com/nnbd_artifacts/3.6.0/dart_sdk.js 43481:18 对象.runZoned 斑点:空/bf8ecf44-b93c-4548-ac5e-c180547a1b46 257:20
Chain.capture 堆栈跟踪被 DartPad 截断和调整...

这个是正确的:

void main() {
  dynamic a = {'a' : {'aa' : 'aa'}, 'b' : 'b', 'c':'c'};
  a['d'] = {'dd':'dd'};
}
dart dynamic
1个回答
0
投票

首先,不要这样做。 我知道在 JS 中拥有混合类型的数据结构是很正常的,但这是 Dart,这应该是例外。

其次,你打字错误。 是的,你的变量

a
是动态的,但实际上你需要的值是动态的,相反,地图被推断为
Map<String,String>
因为这些都是初始值。

要强制 Map 保存任何值,必须这样声明:

Map<String,dynamic> a = {...};

或等效的:

var a = <String,dynamic>{ ... };
© www.soinside.com 2019 - 2024. All rights reserved.