Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

dictionary - How to iterate through single <key, value> pairs of List in dart

I have 2 Lists (uid and url) that are growable, and I need to set the first List as the key and the second as value. At some point, i'll have a 3rd List (randomUids) which will be keys and will print out the corresponding values. Here is the example code:

   List<String> uid = ["uid1", "uid2","uid3","uid4"]; //Lists will grow larger after a while
   List<String> url = ["url1","url2","url3","url4"]; 
   List<String> randomUids = ["uid4", "uid2"]; 

When I try:

   Map<List, List> mapKeyValue = Map();
              mapKeyValue[uid] = url;
     print( uid.contains(randomUids));

I get a false. Also, the print returns uid and url Lists as 2 long indices instead of separate Strings. How can I iterate the List so that url.contains(randomUids) is true. Also how can I print out the values of randomUids.

question from:https://stackoverflow.com/questions/66054612/how-to-iterate-through-single-key-value-pairs-of-list-in-dart

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When I try:

print( uid.contains(randomUids));

I get a false.

Your code asks if uid (a List of Strings) contains randomUids (another List of Strings). It returns false because uid's elements are not Lists; they're Strings.

Presuming that you want the nth element of uid to correspond to the nth element of url, and you can guarantee that uid.length == url.length, you can construct a Map of UIDs to URLs:

assert(uid.length == url.length);
var uidMap = <String, String>{
  for (var i = 0; i < uid.length; i += 1)
    uid[i]: url[i],
};

And then you can iterate over randomUids and do lookups:

for (var uid in randomUids) {
  if (uidMap.containsKey(uid)) {
    print(uidMap[uid]);
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...