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));