現(xiàn)有演示數(shù)組如下:
List<Entity> list = <Entity>[];
Entity entity1 = Entity();
entity1.id = 1;
entity1.name = "1";
list.add(entity1);
Entity entity2 = Entity();
entity2.id = 2;
entity2.name = "2";
list.add(entity2);
...
下面開始幾種常見的數(shù)組操作:
1、flutter獲取數(shù)組中某個對象的index
查詢演示數(shù)組中,id等于2的元素的index。
/// 返回id=2的第一個元素的index,不存在返回-1
int index = list.indexWhere((element) => element.id == 2);
/// 返回id>2的第一個元素的index,不存在返回-1
int index = list.indexWhere((element) => element.id > 2);
indexWhere
查詢出來的是數(shù)組中第一個符合條件的index,如果要獲取符合條件的最后一個元素的index,則需要使用lastIndexWhere
/// 返回id=2的最后一個元素的index,不存在返回-1
int index = list.lastIndexWhere((element) => element.id == 2);
/// 返回id>2的最后一個元素的index,不存在返回-1
int index = list.lastIndexWhere((element) => element.id > 2);
2、flutter獲取數(shù)組中符合條件的某個對象
如獲取演示數(shù)組中,id=2的對象:
/// 返回id=2的最后一個元素
Entity entity = list.lastWhere((element) => element.id == 2)
/// 返回id=2的第一個元素
Entity entity = list.firstWhere((element) => element.id == 2)
/// 返回id>2的最后一個元素
Entity entity = list.lastWhere((element) => element.id > 2)
/// 返回id>2的第一個元素
Entity entity = list.firstWhere((element) => element.id > 2)
3、flutter數(shù)組中是否包含某個元素
如演示數(shù)組中,查看是否有id=2的元素(這里就不使用contains
了):
/// 是否有id=2的元素
bool isContains = list.any((element) => element.id == 2);
/// 是否有id>2的元素
bool isContains = list.any((element) => element.id > 2);
4、flutter刪除數(shù)組中某個特定的元素
如演示數(shù)組中,刪除id=2的元素:
/// 刪除id=2的元素
list.removeWhere((element) => element.id == 2);
/// 刪除id>2的元素
list.removeWhere((element) => element.id > 2);
5、flutter數(shù)組對象中的某一個字段組成新的數(shù)組
如演示數(shù)組中,將所有的id組成新的數(shù)組:
/// 將數(shù)組對象中所有的id組成新的數(shù)組
var newList = list.map((element)=>element.id);
如果將上面得到的結(jié)果,賦值給另一個數(shù)據(jù),可能存在下面的報錯信息:
type 'MappedListIterable<Entity, String>' is not a subtype of type 'List<String>' in type cast
這是類型不對導(dǎo)致的,需要加上toList()
,如下:
var newList = list.map((element)=>element.id).toList();
6、flutter獲取數(shù)組中符合條件的所有元素,組成新的數(shù)組
如演示數(shù)組中,獲取id > 2的所有元素:
/// 獲取id>2的所有元素
var newList = list.where((element) => element.id > 2).toList();
/// 獲取id=2的所有元素
var newList = list.where((element) => element.id = 2).toList();
同上一個問題類型不對,需要加上toList()