如何初始化 map 中的列表?

Map<String,Map<int,List<String>>> myMapList = Map();

我得到一个错误:

The method '[]' was called on null.
I/flutter (16433): Receiver: null
I/flutter (16433): Tried calling: [](9)

推荐答案

只需在创建 map 时添加元素,或稍后通过add次添加元素.例如:

var myMapList = <String, Map<int, List<String>>>{
  'someKey': <int, List<String>>{
    0: <String>['foo', 'bar'],
  },
};

var m2 = <String, Map<int, List<String>>>{}; // empty map
m2['otherKey'] = <int, List<String>>{}; // add an empty map at the top level
m2['otherKey'][2] = <String>[]; // and an empty list to that map
m2['otherKey'][2].add('baz'); // and a value to that list
print(m2);

打印{otherKey: {2: [baz]}}

Dart相关问答推荐

将数据库提供程序导入另一个文件提供程序 dart

禁用 ListView 滚动

VS Code 无法识别 Flutter 中的单元测试

如何从 Dart 中的映射中过滤空值

Flutter android 生成apk

如何用 Flutter 在同屏路由上制作英雄风格的动画?

try 部署到 Google AppEngine 时出现 Dev_appserver.py 错误

如何限制TextSpan小部件的文本长度

如何通过 foreach 函数避免在 dart Map 中使用 await 键

Flutter 在整个屏幕上禁用touch

在Flutter 中使用 import 'dart:html' - 我需要额外的依赖项吗?

如何在Dart中处理JSON

Flutter 中 ListView.builder 中的反向列表

Flutter:如何获取assets目录中所有图像的名称列表?

如何在 showModalBottomSheet 中设置状态

Dart:实例变量在私有类中应该是私有的还是公共的?

基于镜子的反射和传统反射有什么区别?

是否有任何官方计划在 Google App Engine 上支持 Dart?

你如何命名一个 Dart 类?

如何将 `ByteData` 实例写入 Dart 中的文件?