Dart 学习笔记 (三)内置类型 (日期/Map/Set/Runes/Symbol/Enum/Comments)

120 阅读2分钟

日期时间

创建

var now = new DateTime.now(); 
print(now); 

var d = new DateTime(2021, 12, 30); 
print(d);

时间增减量

var d1 = DateTime.now();
print(d1);
print(d1.add(new Duration(minutes: 5)));
print(d1.add(new Duration(minutes: -5)));

比较时间

var d1 = new DateTime(2021, 10, 1);
var d2 = new DateTime(2021, 10, 10);
print(d1.isAfter(d2));
print(d1.isBefore(d2));
var d1 = DateTime.now();
var d2 = d1.add(new Duration(milliseconds: 30));
print(d1.isAtSameMomentAs(d2));

时间戳

var now = new DateTime.now();
print(now.millisecondsSinceEpoch);//- 公元
print(now.microsecondsSinceEpoch);//- 毫秒 更加精确

Map

创建

1. 字面量创建:
  var a = {'a': 'hello', 'b': "world"};
2. 创建不可变的map
  var a = const {'a': 'hello', 'b': "world"};
3. 构造创建:
   - 松散
   var a = new Map();
   - 强类型
   var a = new Map<int, String>();

常用属性 | 名称 | 说明 | | ---------- | --------- | | isEmpty | 是否为空 | | isNotEmpty | 是否不为空 | | keys | key 集合 | | values | values 集合 | | length | 个数 | | entries | 加工数据入口 |

常用方法 名称 | 说明 | | ------------- | ---------- | | addAll | 添加 | | addEntries | 从入口添加 | | containsKey | 按 key 查询 | | containsValue | 按 value 查询 | | clear | 清空 | | remove | 删除某个 | | removeWhere | 按条件删除 | | update | 更新某个 | | updateAll | 按条件更新 | | forEach | 循环遍历 |

Set

声明 Set 是一个元素唯一的有序队列 创建

1. 松散类型
 var a = new Set();
 a.add('java');
 a.add('php');
2. 强制类型
 var b = new Set<String>();
 b.addAll(['dart', 'c#', 'j#', 'e#']);

基本属性 | 名称 | 说明 | | ---------- | ----- | | isEmpty | 是否为空 | | isNotEmpty | 是否不为空 | | first | 第一个 | | last | 最后一个 | | length | 个数 |

常用方法 | 名称 | 说明 | | ------------ | ---------- | | addAll | 添加 | | contains | 查询单个 | | containsAll | 查询多个 | | difference | 集合不同 | | intersection | 交集 | | union | 联合 | | lookup | 按对象查询到返回对象 | | remove | 删除单个 | | removeAll | 删除多个 | | clear | 清空 | | firstWhere | 按条件正向查询 | | lastWhere | 按条件反向查询 | | removeWhere | 按条件删除 | | retainAll | 只保留几个 | | retainWhere | 按条件只保留几个 |

Runes 返回字对象

String a = '👺';
print(a.length);
print(a.runes.length);

>> 输出
2 // 标识占 2 个 16 位字符
1 // 表示占 1 个 32 位字符

枚举 Enum

适合用在常量定义,类型比较很方便。

enum Status { none, running, stopped, paused }\
Status.values.forEach((it) => print('$it - index: ${it.index}'));

注释 Comments

// Symbol libraryName = new Symbol('dart.core');\

多行注释

/*
 * Symbol
 * 
Symbol libraryName = new Symbol('dart.core');
MirrorSystem mirrorSystem = currentMirrorSystem();
LibraryMirror libMirror = mirrorSystem.findLibrary(libraryName);
libMirror.declarations.forEach((s, d) => print('$s - $d')); 
*/

文档注释

/// `main` 函数
///
/// 符号
/// 枚举
///
void main() {
  ...
}