dart中的循环

更新时间:2023-05-25 21:55

本节对循环语句进行总结,包括以下几种:

for循环

List myList = [1, 2, 3, 4];

List newList = new List();
for(var i=0; i<myList.length;i++){
  newList.add(myList[i]*2);
}

for..in..

List myList = [1, 2, 3, 4];

List newList = new List();
for(var i in myList){
  newList.add(myList[i]*2);
}

forEach

List myList = [1, 2, 3, 4];

myList.forEach((v) {
  print(v);
});

map

返回一个数组

var newList = myList.map((v) {
  return v * 2;
});

print(newList.toList());

where

返回满足条件的值

List myList2 = [1, 2, 3, 4, 5, 6, 7];

var newList2 = myList.where((v) {
  return v > 5;
});

print(newList2.toList()); // 6,7

any

只要有一个满足条件就返回true

var f = myList.any((v) {
  return v > 5;
});

print(f); // true

every

条件都满足了才能返回true 否则返回false

var f2 = myList.any((v) {
  return v > 5;
});

print(f2); // fasle