Dart Basics - Collection Types
1. Definition of collection type
For collection types, Dart has the most commonly used three built-in: List / Set / Map
.
Among them, List
it can be defined as follows:
// List定义// 1.使用类型推断定义
var letters = ['a', 'b', 'c', 'd'];
print('$letters ${
letters.runtimeType}');
// 2.明确指定类型
List<int> numbers = [1, 2, 3, 4];print('$numbers ${
numbers.runtimeType}');
Among them, set
it can be defined as follows:
- In fact, it's just a matter of
[]
replacing it{}
. Set
The twoList
biggest differences are:Set
it is unordered, and the elements are not repeated.
// Set的定义
// 1.使用类型推导定义
var lettersSet = {
'a', 'b', 'c', 'd'};
print('$lettersSet ${
lettersSet.runtimeType}');
// 2.明确指定类型
Set<int> numbersSet = {
1, 2, 3, 4};
print('$numbersSet ${
numbersSet.runtimeType}');
Finally, Map
there is the dictionary type we often say, and its definition is as follows:
// Map的定义
// 1.使用类型推导定义
var infoMap1 = {
'name': 'why', 'age': 18};
print('$infoMap1 ${
infoMap1.runtimeType}');
// 2.明确指定类型
Map<String, Object> infoMap2 = {
'height': 1.88, 'address': '北京市'};
print('$infoMap2 ${
infoMap2.runtimeType}');
2. Common operations on collections
After understanding how these three collections are defined, let's look at some of the most basic public operations
The first category is the property of getting the length supported by all collections length
:
// 获取集合的长度
print(letters.length);
print(lettersSet.length);
print(infoMap1.length);
The second category, is add/remove/include operations
- And,
List
for the element is ordered, it also provides a method to delete the element at the specified index position
// 添加/删除/包含元素
numbers.add(5);
numbersSet.add(5);
print('$numbers $numbersSet');
numbers.remove(1);
numbersSet.remove(1);
print('$numbers $numbersSet');
print(numbers.contains(2));
print(numbersSet.contains(2));
// List根据index删除元素
numbers.removeAt(3);
print('$numbers');
The third category, yes Map
operation
- Since it has a key and a value, whether it is reading a value or operating, it must be clearly based on the key, or the value, or the key/value pair.
// Map的操作
// 1.根据key获取
valueprint(infoMap1['name']);
// 2.获取所有的entries
print('${
infoMap1.entries} ${
infoMap1.entries.runtimeType}');
// 3.获取所有的keys
print('${
infoMap1.keys} ${
infoMap1.keys.runtimeType}');
// 4.获取所有的values
print('${
infoMap1.values} ${
infoMap1.values.runtimeType}');
// 5.判断是否包含某个key或者value
print('${infoMap1.containsKey('age')} ${
infoMap1.containsValue(18)}'); // true true
// 6.根据key删除元素
infoMap1.remove('age');print('${
infoMap1}');
reference:
Teacher Coderwhy 's official account