概述
本文向您展示了从 Flutter 中的列表中删除重复项的 2 种方法。第一个适用于原始数据类型列表。第二个稍微复杂一些,但适用于map****列表或对象列表。
转换为 Set 然后反转为 List
这是一个简单列表的简单快速的解决方案。
例子:
void main(){
final myNumbers = [1, 2, 3, 3, 4, 5, 1, 1];
final uniqueNumbers = myNumbers.toSet().toList();
print(uniqueNumbers);
final myStrings = ['a', 'b', 'c', 'a', 'b', 'a'];
final uniqueStrings = myStrings.toSet().toList();
print(uniqueStrings);
}
输出:
[1, 2, 3, 4, 5]
[a, b, c]
从map或对象列表中删除重复项
我们的策略是将列表的每个项目转换为 JSON 字符串,然后像第一种方法一样使用toSet()和toList()。
例子:
import "dart:convert";
void main(){
final myList = [
{
'name': 'Andy',
'age': 41
},
{
'name': 'Bill',
'age': 43
},
{
'name': 'Andy',
'age': 41
}
];
// convert each item to a string by using JSON encoding
final jsonList = myList.map((item) => jsonEncode(item)).toList();
// using toSet - toList strategy
final uniqueJsonList = jsonList.toSet().toList();
// convert each item back to the original form using JSON decoding
final result = uniqueJsonList.map((item) => jsonDecode(item)).toList();
print(result);
}
输出:
[{name: Andy, age: 41}, {name: Bill, age: 43}]
最后
以上就是幽默丝袜为你收集整理的从Dart列表中删除重复项的2种方法的全部内容,希望文章能够帮你解决从Dart列表中删除重复项的2种方法所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复