[英]In dart how add multiple list in a list?
I want to add multiple List in a List.我想在一个列表中添加多个列表。 The Length of the Outer loop is 2 and the length of the inner loop is 2.
外环的长度为 2,内环的长度为 2。
List matchName = [];
List a = [];
List b = [];
void getMatchName(GetUserMatchModelRes m) {
matchName.clear();
for (var i = 0; i < m.ObjectList.length; i++) {
matchName.clear();
matchName.add(
m.ObjectList[i].ContactName,
);
print("i:$i");
for (var j = 0; j < m.ObjectList[i].ContactPhones.length; j++) {
print("j:$j");
matchName.add(
m.ObjectList[i].ContactPhones[j].MatchedContactName,
);
}
a.add(matchName);
print(a);
}
}
Output when outer loop is 0: [[a,b,c]]
Output 当外循环为 0 时:
[[a,b,c]]
When outer loop is 1: [[d,e,f],[d,e,f]]
当外循环为 1 时:
[[d,e,f],[d,e,f]]
But I want [[a,b,c],[d,e,f]]
但我想要
[[a,b,c],[d,e,f]]
How I can achieve this?我怎样才能做到这一点?
You're essentially doing:你本质上是在做:
var outer = <List<String>>[];
var inner = ['foo'];
outer.add(inner);
outer.add(inner);
Now outer
has two elements that refer to the same object:现在
outer
有两个元素指向同一个object:
+---+---+
outer: | | |
+-|-+-|-+
| |
v v
+-------+
inner: | 'foo' |
+-------+
If you modify inner
, you'll see the change in both outer[0]
and in outer[1]
.如果您修改
inner
,您将在outer[0]
和outer[1]
中看到变化。
To avoid this, you need to add separate objects so that they can be modified independently.为避免这种情况,您需要添加单独的对象,以便可以独立修改它们。 Either create new lists to add instead of modifying an existing one:
创建新列表以添加而不是修改现有列表:
var outer = <List<String>>[];
outer.add(['foo']);
outer.add(['foo']);
or add copies:或添加副本:
var outer = <List<String>>[];
var inner = ['foo'];
outer.add([...inner]);
outer.add([...inner]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.