Dart核心库常见方法学习

这几篇关于Dart的文章,只是在看官网教程的时候敲一遍巩固记忆而写的

Dart:core

每个文件都会默认引入这个包,包括numbers,collections,strings等等

print

打印,默认会调用打印的对象的 toString 方法

1
2
3
print(anObject)
const name = 'Jsonz'
print('I\'m $name');

Numbers

parse

解析把字符串转为数字

1
2
3
4
5
6
7
assert(int.parse('42') == 42);
assert(int.parse('0x42') == 66);
assert(double.parse('0.50') == 0.5);
assert(num.parse('42') is int);
assert(num.parse('0x42') is int);
assert(num.parse('0.50') is double);
assert(int.parse('42', radix: 16) == 66);

toString

将数字转为字符串

1
2
3
4
5
6
7
8
9
10
11
12
// Convert an int to a string.
assert(42.toString() == '42');

// Convert a double to a string.
assert(123.456.toString() == '123.456');

// Specify the number of digits after the decimal.
assert(123.456.toStringAsFixed(2) == '123.46');

// Specify the number of significant figures.
assert(123.456.toStringAsPrecision(2) == '1.2e+2');
assert(double.parse('1.2e+2') == 120.0);

String

search inside a string

字符串的查找搜索

1
2
3
4
5
var str = 'Never odd or even';
assert(str.contains('odd'));
assert(str.startsWith('Never'));
assert(str.endsWith('even'));
assert(str.indexOf('odd') == 6);

Extracting data from a string

从字符串提取数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var str = 'Never odd or even';
assert(str.substring(6, 9) == 'odd');

var parts = str.split(' ');
assert(parts.length == 4);
assert(parts[0] == 'Never');

assert(str[0] == 'N');
for (var char in 'hello'.split('')) {
print(char);
}

var codeUnitList = str.codeUnits.toList();
assert(codeUnitList[0] == 78);

converting to uppercase or lowercase

切换大小写

1
2
3
var str = 'Never odd or even';
assert(str.toUpperCase() == 'NEVER ODD OR EVEN');
assert(str.toLowerCase() == 'never odd or even');

trimming && empty

1
2
3
assert('   hello '.trim() == 'hello');
assert(''.isEmpty);
assert(' '.isNotEmpty);

replace

1
2
3
4
var greetingTemplate = 'Hello, Name!';
var greeting = greetingTemplate.replaceAll(RegExp('Name'), 'Bob');
print(greeting); // Hello, Bob!
assert(greeting != greetingTemplate);

building a string

在调用toString之前不会生成新的字符串对象。

1
2
3
4
5
6
7
8
9
var sb = StringBuffer();

sb
..write('use a stringBuffer for ')
..writeAll(['efficient', 'string', 'creation'], '')
..write('.');

var fullString = sb.toString();
assert(fullString == 'Use a StringBuffer for efficient string creation.');

正则

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
final numbers = RegExp(r'\d+');

const allCharacters = 'llamas live fifteen to twenty years';
const someDigits = 'llamas live 15 to 20 years';

assert(!allCharacters.contains(numbers));
assert(someDigits.contains(numbers));

final exedOut = someDigits.replaceAll(numbers, 'XX');
assert(exedOut == 'llamas live XX to XX years');

assert(numbers.hasMatch(someDigits));

for (var match in numbers.allMatches(someDigits)) {
print(match.group(0));
}

Collections

List、Set、Map

List

普通数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// 基础操作
listBase() {
// Use a List constructor.
var vegetables = List();
assert(vegetables.length == 0);

// simply use a list literal.
var fruits = ['apples', 'oranges'];
// add to a list.
fruits.add('kiwis');
// add multiple items to a list.
fruits.addAll(['grapes', 'bananas']);

// Get the list length.
assert(fruits.length == 5);

// remove a single item.
var appleIndex = fruits.indexOf('apples');
fruits.removeAt(appleIndex);
assert(fruits.length == 4);

// remove all elements from a list
fruits.clear();
assert(fruits.length == 0);

assert(fruits[0] == 'apples');
assert(fruits.indexOf('apples') == 0);
}

// sort 方法
listSort() {
var fruits = ['bananas', 'apples', 'oranges'];
// Sort a list.
fruits.sort((a, b) => a.compareTo(b));
assert(fruits[0] == 'apples');
}

// list type
listType() {
var fruits = List<String>();
fruits.add('apples');
var fruit = fruits[0];
assert(fruit is String);
}

Set

去重类数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Set base
setBase() {
var ingredients = Set();
ingredients.addAll(['gold', 'titanium', 'xenon']);
assert(ingredients.length == 3);

ingredients.add('gold');
assert(ingredients.length == 3);

ingredients.remove('gold');
assert(ingredients.length == 2);
}

// 是否包含
setContains() {
var ingredients= Set();
ingredients.addAll(['gold', 'titanium', 'xenon']);

// check whether an item is in the set.
assert(ingredients.contains('titanium'));

// check whether all the items are in the set.
assert(ingredients.containsAll(['titanium', 'xenon']));
}

// 交集
setIntersection() {
var ingredients= Set();
ingredients.addAll(['gold', 'titanium', 'xenon']);

// create the intersection of thw sets.
var nobleGases = Set.from(['xenon', 'argon']);
var intersection = ingredients.intersection(nobleGases);

assert(intersection.length == 1);
assert(intersection.contains('xenon'));
}

关于Set的更多方法

Maps

js对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// 基础创建
mapBase() {
var hawaiianBeaches = {
'Oahu': ['Waikiki', 'Kailua', 'Waimanalo'],
'Big Island': ['Wailea bay', 'Pololu Beach'],
'Kauai': ['Hanalei', 'Poipu'],
};

var searchTerms = Map();

var nobleGases = Map<int, String>();
}

// 移除
mapRemove() {
var nobleGases = {
54: 'xenon',
};
assert(nobleGases[54] == 'xenon');
assert(nobleGases.containsKey(54));

nobleGases.remove(54) ;
assert(!nobleGases.containsKey(54));
}

// keys && values
mapKeyValue() {
var hawaiianBeaches = {
'Oahu': ['Waikiki', 'Kailua', 'Waimanalo'],
'Big Island': ['Wailea bay', 'Pololu Beach'],
'Kauai': ['Hanalei', 'Poipu'],
};

// keys
var keys = hawaiianBeaches.keys;
assert(keys.length == 3);
assert(Set.from(keys).contains('Oahu'));

// values
var values = hawaiianBeaches.values;
assert(values.length == 3);
assert(values.any((v)=> v.contains('Waikiki')));

// check a keys
assert(hawaiianBeaches.containsKey('Oahu'));
assert(!hawaiianBeaches.containsKey('Florida'));

// putIfAbsent 当且仅当没有该Key赋值,才会执行该函数
var teamAssignments = {};
teamAssignments.putIfAbsent('Catcher', ()=> 'test');
assert(teamAssignments['Catcher'] != null);
}

更多关于Maps的API

通用(Map,Set,List)的方法

Iterable(迭代器)方法指Set和List,因为他们是继承Iterable class
Collections指 Set、List和Map.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
commonSetList() {

//Iterables 指的是List和Set,因为都是继承该类实现的
// Collections 指的是List,Set,Map

var coffees = [];
var teas = ['green', 'black', 'chamomile', 'earl grey'];
var teasSet = {'green', 'black'};
var teasMap = {
'tea1': 'green',
'tea2': 'black',
};

// Iterables: isEmpty isNotEmpty
assert(coffees.isEmpty);
assert(teas.isNotEmpty);
assert(teasSet.isNotEmpty);

// Collections: forEach
teas.forEach((tea)=> {
print('I drink $tea')
});
teasMap.forEach((teaKey, teaValue)=> {
print('$teaKey, $teaValue')
});

// Iterbables: map. map使用的是惰性模式,即在上一个返回之前,不会执行下一个函数
var loudTeas = teas.map((tea)=> tea.toUpperCase());
loudTeas.forEach(print);

// 如果想要立即执行,可以使用 toList 或 toSet
var loudTeas2 = teas.map((tea)=> tea.toUpperCase()).toList();
print(loudTeas2);

// where any every 和js一样的功能,分别是查找所有符合的,有任意符合返回true,所有符合返回true
bool isDecaffeinated(String teaName)=> teaName == 'chamomile';
var decaffeinatedTeas = teas.where(isDecaffeinated);
print(decaffeinatedTeas);
assert(teas.any(isDecaffeinated));
assert(!teas.every(isDecaffeinated));
}

URI

URI主要提供一些解码和编码url的功能

解码与编码

1
2
3
4
5
6
7
8
9
10
11
12
13
encodeAndDecode() {
var uri = 'http://example.org/api?foo=some message';
var encoded = Uri.encodeFull(uri);
assert(encoded == 'http://example.org/api?foo=some%20message');

var decode = Uri.decodeFull(encoded);
assert(uri == decode);

var encodeComponent = Uri.encodeComponent(uri);
assert(encodeComponent == 'http%3A%2F%2Fexample.org%2Fapi%3Ffoo%3Dsome%20message');
var decoded = Uri.decodeComponent(encodeComponent);
assert(uri == decoded);
}

解析与构建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
parseAndBuild() {
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 == 'frage');
assert(uri.origin == 'http://example.org:8080');

var buildUri = Uri(
scheme: 'http',
host: 'example.org',
path: '/foo/bar',
fragment: 'frag'
);
assert(buildUri.toString() == 'http://example.org/foo/bar#frag');
}

Dates and times

时间日期相关

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
date() {
var now = DateTime.now();

// create a now DateTime with the local time zone.
var y2k = DateTime(2000);

// 指定月份和日期
y2k = DateTime(2000, 1, 2);

// specify the date as a UTC time.
y2k = DateTime.utc(2000);

// Specify a date and time in ms since the Unix epoch.
y2k = DateTime.fromMillisecondsSinceEpoch(946684800000, isUtc: true);

// Parse an ISO 8601 date
y2k = DateTime.parse('2000-01-01T00:00:00Z');

// 返回从1970到目标的毫秒数
y2k = DateTime.utc(2000);
assert(y2k.millisecondsSinceEpoch == 946684800000);

var unixEpoch = DateTime.utc(1970);
assert(unixEpoch.millisecondsSinceEpoch == 0);
}

// 时间操作方法
dateOptions() {
var y2k = DateTime.utc(2000);
print(Duration(days: 366));
var y2001 = y2k.add(Duration(days: 366));
assert(y2001.year == 2001);

// subtract 30 days
var december2000 = y2001.subtract(Duration(days: 30));
assert(december2000.year == 2000);
assert(december2000.month == 12);

// Calculate the difference between two dates.
// Returns a Duration object.
var duration = y2001.difference(y2k);
assert(duration.inDays == 366);
}

更多DateTime API
更多Duration API

未完待续