flutter Dart -以列表作为值的Map

ff29svar  于 2022-11-17  发布在  Flutter
关注(0)|答案(1)|浏览(181)

我有这个:

List<ForumCategories>? forumCategories;
  var mainCats = List<ForumCategories>.empty(growable: true);
  var subCats = <int, List<ForumCategories>>{};

这就是我所做的,以填充它:

for (var i = 0; i < forumCategories!.length; i++) {
  if (forumCategories![i].main == 0) {
    subCats[forumCategories![i].slave]?.add(forumCategories![i]);
  }
}

而比我做的时候:

var size = subCats.length;
print("SUBCATS: $size");

输出始终为:SUBCATS: 0
Map上没有这个。知道为什么吗?

b09cbbtk

b09cbbtk1#

因为您正尝试将项目添加到空List,请参见此处:

if (forumCategories![i].main == 0) {
subCats[forumCategories![i].slave]?.add(forumCategories![i]);
}

subCats[forumCategories![i].slave]尚未存在于您的Map中,这就像您说:

null.add(forumCategories![i]);

什么都不会发生。你需要用一个空的List来初始化它,如果它是null的话,如下所示:

if (forumCategories![i].main == 0) {

(subCats[forumCategories![i].slave] ?? []).add(forumCategories![i]) // this will assign an empty list only the first time when it's null, then it adds elements to it.
 }

现在,在将元素添加到该列表之前,它将找到要添加的空列表。

相关问题