Dart的List比较特殊的几个API

List里面常用的属性和方法:

  • 常用属性:

length 长度
reversed 翻转
isEmpty 是否为空
isNotEmpty 是否不为空

  • 常用方法:

add 增加
addAll 拼接数组
indexOf 查找 传入具体值
remove 删除 传入具体值
removeAt 删除 传入索引值
fillRange 修改
insert(index,value); 指定位置插入
insertAll(index,list) 指定位置插入List
toList() 其他类型转换成List
join() List转换成字符串
split() 字符串转化成List


上面的这些API在其他语言中也类似。下面列举几个比较特殊一点的。

  • foreach

void main() {

  List myList = ["香蕉","苹果","西瓜"];

  myList.forEach((i) {
    print("$i");
  });
  
}
  • map

void main() {

  List oldList = [1,2,3];

  List newList = oldList.map((i) {
    return i * 2;
  }).toList();

  print(newList);

}

// 输出结果:[2, 4, 6]
  • where

void main() {

  List oldList = [1,2,3,4,5,6,7,8,9];

  List newList = oldList.where((i) {
    return i > 5;
  }).toList();

  print(newList);

}

// 输出结果:
[6, 7, 8, 9]

  • any

void main() {

  List oldList = [1,2,3,4,5,6,7,8,9];

  bool result = oldList.any((i) {  // 只要集合里面有满足条件的就返回true
    return i > 5;
  });

  print(result);

}

// 输出结果:true
  • every

void main() {

  List oldList = [1,2,3,4,5,6,7,8,9];

  bool result = oldList.every((i) {  // 集合里面每一个都满足条件时就返回true
    return i > 5;
  });

  print(result);

}

// 输出结果:false

 

原文地址:https://www.cnblogs.com/chichung/p/11971980.html