1. 变量声明

如何定义变量

代码如下:

var name = 'Bob';

变量的初始值

代码如下:

int lineCount;
assert(lineCount == null); // Variables (even numbers) are initially null.

可以使用var,也可以直接指定类型。
final, 定义为final的变量,值不能够被更改

代码如下:

final name = 'Bob'; // Or: final String name = 'Bob';
name = 'Alice'; // ERROR

2. 基础类型

字符串

字符串可以使用单引号或者双引号。

代码如下:

var s1 = 'Single quotes work well for string literals.';
var s2 = "Double quotes work just as well.";


在字符串中,可以直接应用值, ${表达式}, 如果只是一个变量,就可以去掉{}
代码如下:

var s = 'string interpolation';
assert('Dart has $s, which is very handy.' ==
'Dart has string interpolation, which is very handy.');
assert('That deserves all caps. ${s.toUpperCase()} is very handy!' ==
'That deserves all caps. STRING INTERPOLATION is very handy!');


多行字符串,会被认为默认拼接。
代码如下:

var s = 'String ''concatenation'
" works even over line breaks.";
assert(s == 'String concatenation works even over line breaks.');

如果要使用多行字符串,可以这样, 用'''

代码如下:

var s1 = '''
You can create
multi-line strings like this one.
''';


创建一个不考虑转义的字符串
代码如下:

var s = @"In a raw string, even \n isn't special.";

StringBuffer, 非常类似.net中的。

代码如下:

var sb = new StringBuffer();

sb.add("Use a StringBuffer ");
sb.addAll(["for ", "efficient ", "string ", "creation "]);
sb.add("if you are ").add("building lots of strings.");

var fullString = sb.toString();

数字

主要就2种,int 和 double, 它们都继承num类型

数字和字符串之间的转换

代码如下:

// String -> int
var one = Math.parseInt("1");
assert(one == 1);

// String -> double
var onePointOne = Math.parseDouble("1.1");
assert(onePointOne == 1.1);

// int -> String
var oneAsString = 1.toString();
assert(oneAsString == "1");

// double -> String
var piAsString = 3.14159.toStringAsFixed(2);
assert(piAsString == "3.14");



布尔类型

bool,不同于js, 只要不是true, 那么就都是false.

Lists(可以当做数组)

代码如下:

var list = [1,2,3]; //实例化一个list
list.add(4); //添加一个元素4

可以使用for, for...in, foreach()来遍历一个list.

代码如下:

var list = [1,2,3];
for (final x in list) {
print(x);
}


或者

代码如下:

var list = [1,2,3];
list.forEach((element) => print(element));

Maps(字典类型)

代码如下:

var gifts = { // A map literal
// Keys Values
"first" : "partridge",
"second" : "turtledoves",
"fifth" : "golden rings"};

gifts["third"] = "apple"; //添加一个

使用foreach遍历

代码如下:

var gifts = {
"first" : "partridge",
"second": "turtledoves",
"fifth" : "golden rings"};
gifts.forEach((k,v) => print('$k : $v'));

getKeys()和getValues()方法

代码如下:

var gifts = {"first": "partridge", "second": "turtledoves"};
var values = gifts.getValues();

//Print partridge and turtledoves, but not necessarily in that order.
values.forEach((v) => print(v));

09-18 12:58