本教程展示了在Dart或flutter编程中将List转换为Set的多种方法。
在Dart中,List是一个对象的动态集合,元素按插入顺序插入,并允许重复对象。Set是一个数据结构,用于存储元素的集合,不允许重复。
两者在Dart或Flutter中都是不同的类型,我们必须写一段代码,将一种类型转换为另一种。
在Dart或Flutter编程中如何将List转换为Set
传播运算符(...)用于传播数值,并将其分配给Set Literal语法。
下面是一个示例程序
main() {
List wordsList = ['one', 'two', 'three'];
print(wordsList); //[one, two, three]
print(wordsList.runtimeType); //JSArray
var wordsSet = {...wordsList};
print(wordsSet); //{one, two, three}
print(wordsSet.runtimeType); //_LinkedHashSet
print(wordsSet is Set); //true
}
输出:
[one, two, three]
JSArray
{one, two, three}
_LinkedHashSet
true
如何在Dart或Flutter编程中把Set转换为List?
Set.toList() 用于将Set转换为List的方法
下面是一个将Set转换为独立列表的示例程序。
main() {
Set words = {'one', 'two', 'three'};
List lists = words.toList();
print(words.runtimeType); //_LinkedHashSet
print(lists.runtimeType); //JSArray
}
总结
学习如何在Dart或flutter编程中把List转换为Set或Set转换为List。