dart:core
该库包含内置类型,集合和其他核心函数,该库是自动加入到每个dart程序中的。
Numbers和Booleans
boolean Number类型只有两种,不再有那么多了,是不是很开心?
Strings和正则
String是一个不可变的类,和Java一样,有很多方法,自行琢磨。
RegExp实现了Dart的正则表达式。
```dart var numbers = new RegExp(r'\d+');
var allCharacters = 'llamas live fifteen to twenty years'; var someDigits = 'llamas live 15 to 20 years';
// contains() can use a regular expression. assert(!allCharacters.contains(numbers)); assert(someDigits.contains(numbers));
// Replace every match with another string. var exedOut = someDigits.replaceAll(numbers, 'XX'); assert(exedOut == 'llamas live XX to XX years');
## 集合
Lists、Sets、Maps
Lists有时也称为Array,有序。
```dart
List superheroes = [ 'Batman', 'Superman', 'Harry Potter' ];
Set villains = new Set();
villains.add('Joker');
villains.addAll( ['Lex Luther', 'Voldemort'] );
Map sidekicks = { 'Batman': 'Robin',
'Superman': 'Lois Lane',
'Harry Potter': 'Ron and Hermione' };
常见集合方法
where()、any()、every() (Kotlin中也有这些鬼)
URIs
Uri类提供了编解码URI的函数。
//编解码整个URI
var uri = 'http://example.org/api?foo=some message';
var encoded = Uri.encodeFull(uri);
assert(encoded ==
'http://example.org/api?foo=some%20message');
var decoded = Uri.decodeFull(encoded);
assert(uri == decoded);
//编解码URI的部分组成
var uri = 'http://example.org/api?foo=some message';
var encoded = Uri.encodeComponent(uri);
assert(encoded ==
'http%3A%2F%2Fexample.org%2Fapi%3Ffoo%3Dsome%20message');
var decoded = Uri.decodeComponent(encoded);
assert(uri == decoded);
//解析URI
var uri =
Uri.parse('http://example.org:8080/foo/bar#frag');
assert(uri.scheme == 'http');
assert(uri.host == 'example.org');
assert(uri.path == '/foo/bar');
assert(uri.fragment == 'frag');
assert(uri.origin == 'http://example.org:8080');
Dates和Times
DateTime是一个点时间,DateTime.now()可以获取当前日期和时间。
工具类
dart:async
异步程序通常使用回调,但是dart提供了一种替代方案:Future和Stream。Future类似一个做出了以后会返回某一结果的诺言,Stream是一种能获取一系列值的方法。
需要使用异步库时,需要在文件头导入库:
Future
await表达式
await表达式比Future API更好理解。
runUsingAsyncAwait() async {
// ...
var entryPoint = await findEntryPoint();
var exitCode = await runExecutable(entryPoint, args);
await flushThenExit(exitCode);
}
基本用法
可以使用then()来执行future的结果。比如说HttpRequest.getString()返回一个Future,使用then()来执行http响应,
HttpRequest.getString(url).then((String result) {
print(result);
}).catchError((e) {
// Handle or ignore the error.
});
then().catchError()模式是异步版本的try-catch。
组合多个异步方法
Future result = costlyQuery(url);
result
.then((value) => expensiveWork(value))
.then((_) => lengthyComputation())
.then((_) => print('Done!'))
.catchError((exception) {
/* Handle exception... */
});
//等价于
try {
final value = await costlyQuery(url);
await expensiveWork(value);
await lengthyComputation();
print('Done!');
} catch (e) {
/* Handle exception... */
}
等待多个futures
有时,你需要调用多个Future,然后等待结果再执行。(Java中的栅栏)使用Future.wait()静态方法里管理多个Futures,然后等待他们执行完成。
Future deleteLotsOfFiles() async => ...
Future copyLotsOfFiles() async => ...
Future checksumLotsOfOtherFiles() async => ...
await Future.wait([
deleteLotsOfFiles(),
copyLotsOfFiles(),
checksumLotsOfOtherFiles(),
]);
print('Done with all the long steps!');
Stream
使用异步循环
await for代替Stream API。下面的例子使用Stream的listen()方法订阅了一系列文件,搜索文件
FileSystemEntity.isDirectory(searchPath).then((isDir) {
if (isDir) {
final startingDir = Directory(searchPath);
startingDir
.list(
recursive: argResults[recursive],
followLinks: argResults[followLinks])
.listen((entity) {
if (entity is File) {
searchFile(entity, searchTerms);
}
});
} else {
searchFile(File(searchPath), searchTerms);
}
});
//等价于
Future main(List<String> arguments) async {
// ...
if (await FileSystemEntity.isDirectory(searchPath)) {
final startingDir = Directory(searchPath);
await for (var entity in startingDir.list(
recursive: argResults[recursive],
followLinks: argResults[followLinks])) {
if (entity is File) {
searchFile(entity, searchTerms);
}
}
} else {
searchFile(File(searchPath), searchTerms);
}
}
监听流数据
使用await for或listen()方法监听数据的到来:
querySelector('#submitInfo').onClick.listen((e) {
// When the button is clicked, it runs this code.
submitData();
});
转换数据
transform()
dart:math
三角函数
assert(cos(pi) == -1.0);
// Sine
var degrees = 30;
var radians = degrees * (pi / 180);
// radians is now 0.52359.
var sinOf30degrees = sin(radians);
// sin 30° = 0.5
assert((sinOf30degrees - 0.5).abs() < 0.01);
最大值和最小值
assert(max(1, 1000) == 1000);
assert(min(1, -1000) == -1000);
常量
print(e); // 2.718281828459045
print(pi); // 3.141592653589793
print(sqrt2); // 1.4142135623730951
随机数
var random = Random();
random.nextDouble(); // Between 0.0 and 1.0: [0, 1)
random.nextInt(10); // Between 0 and 9.
dart:convert
import 'dart:convert';
编解码JSON
解码:
var jsonString = '''
[
{"score": 40},
{"score": 80}
]
''';
var scores = jsonDecode(jsonString);
assert(scores is List);
var firstScore = scores[0];
assert(firstScore is Map);
assert(firstScore['score'] == 40);
编码:
var scores = [
{'score': 40},
{'score': 80},
{'score': 100, 'overtime': true, 'special_guest': null}
];
var jsonText = jsonEncode(scores);
assert(jsonText ==
'[{"score":40},{"score":80},'
'{"score":100,"overtime":true,'
'"special_guest":null}]');