Dart 基礎 - 1

Dart Basic - 1

Posted by Bobson Lin on Friday, March 8, 2019

內建型別 (Built-in types)

Dart 內建型別全都繼承於 Object,都視為是物件。

Dart 內建型別有下列幾種:

  • Number - (int, double) num
  • Boolean - true 或 false
  • List - Collections of items (aka arrays)
  • Set - Collection of unique items (Dart 2.2 正式引入)
  • Map - Collections with associated Key Value Pairs
  • String - “Hello!” (single and double quotes)
  • Rune - unicode character points
  • Symbol - #symbol (simbolic metadata)

Number

num 包含了兩種型別 int, double

int x = 1;
int hex = 0xFA;
print("int: $x, hex int: $hex");

double y = 1.1;
double exponents = 1.42e5;
print("double: $y, exponents: $exponents");

// String <=> int

int one = int.parse('1');
assert(one == 1);
String oneAsString = 1.toString();
assert(oneAsString == '1');

// String <=> double

double onePointOne = double.parse('1.1');
assert(onePointOne == 1.1);
String piAsString = 3.14159.toStringAsFixed(2);
assert(piAsString == '3.14');
int: 1, hex int: 250
double: 1.1, exponents: 142000.0

Boolean

// Bitwise 運算

assert((3 << 1) == 6); // 0011 << 1 == 0110  

assert((3 >> 1) == 1); // 0011 >> 1 == 0001

assert((3 | 4) == 7); // 0011 | 0100 == 0111


// Check for zero.  

int hitPoints = 0;
assert(hitPoints <= 0);
print("hitPoints <= 0? ${hitPoints <= 0}");
hitPoints <= 0? true

List

List, Set, Map 都源自於 Iterable
所以他們很多共同函數,像是 forEach, map 等等…

print("\nDart List:");
// List & Generics(泛型)

List<String> fruits = ['bananas', 'grapes', 'oranges'];
print(fruits);
print("fruits.length: ${fruits.length}");
print("fruits[1]: ${fruits[1]}");

fruits[1] = "apples";
print(fruits);

fruits.sort();
print(fruits);

fruits = fruits.map((String fruit) {
  return fruit.substring(0, fruit.length - 1);
}).toList();
print(fruits);
Dart List:
[bananas, grapes, oranges]
fruits.length: 3
fruits[1]: grapes
[bananas, apples, oranges]
[apples, bananas, oranges]
[apple, banana, orange]

泛型(Generic):

Set

print("\nDart Set:");

// Set 鹵元素 氟氯溴碘砈

Set<String> halogens = {'fluorine', 'chlorine', 'bromine', 'iodine', 'astatine'};
print(halogens);

var elements = <String>{};
elements.add('fluorine');
elements.addAll(halogens);
Dart Set:
{fluorine, chlorine, bromine, iodine, astatine}

Map

print("\nDart Map:");

// Map

Map gifts = {
  'first': 'partridge',
  'second': 'turtledoves',
  'fifth': 'golden rings'
};
print("gifts.length: ${gifts.length}");
print("gifts['first']: ${gifts['first']}");

// 惰性氣體

Map<int, String> nobleGases = {
  2: 'helium',
  10: 'neon',
  18: 'argon',
};
print(nobleGases.containsValue("argon"));
Dart Map:
gifts.length: 3
gifts['first']: partridge
true

String

String str1 = "It's a string with double quotes";
String str2 = 'It\'s a string with single quote';
String str3 = """  
It's a long string with triple double quotes  
這是一個很長的字串
""";
print(str1);
print(str2);
print(str3);

const aConstNum = 0;
const aConstBool = true;
const aConstString = 'a constant string';

var aNum = 0;
var aBool = true;
var aString = 'a string';
const aConstList = [1, 2, 3];

const validConstString = '$aConstNum $aConstBool $aConstString';
// const invalidConstString = '$aNum $aBool $aString $aConstList';

print("validConstString: $validConstString");
print("$aNum $aBool $aString $aConstList, ${aConstList[0]}");
It's a string with double quotes
It's a string with single quote
  It's a long string with triple double quotes
  這是一個很長的字串
  
validConstString: 0 true a constant string
0 true a string [1, 2, 3], 1

函數(Function)

Dart 的 Function 也繼承於 Object,是可以實例化的物件。
所以可以作任何跟內建型別一樣的操作,例如指定變數為 Function 或 屬於其他物件的一部分

程式語言中的函數與數學中的函數概念類似,透過帶入參數進行一連串的任務(運算)後得到回傳值。 標準形式 funcName(param1, param2) { return retValue; }

函數大都會有個 函數名稱 (funcName),小括號內則是放帶入此函數的 參數 (param),
函數執行的任務會放在大括號內部,最後會有個 回傳值 (retValue)

print("\nDart Function:");
// Function

dynamic_add(a, b) {
  return a + b;
}
print(dynamic_add(1, 2));
print(dynamic_add(20.0, 40.0));
print(dynamic_add("a", "b"));

int add(int a, int b) {
  return a + b;
}

Function func = add;
var result = func(20, 30);
print("func result is $result");

Map ops = {
  'add': add,
  'sub': (int a, int b) => a - b,
};
result = ops['sub'](6, 10);
print("ops sub result: $result");
Dart Function:
3
60.0
ab
func result is 50
ops sub result: -4

當然凡是都有些例外或是撇步(方便寫少一點 或 增加易讀性)

  1. 回傳空值或不回傳東西的函數 (void function)
  2. 匿名函數 (anonymous function)
  3. => expr 取代 { retrun expr; } (express function)

你也可以瞧瞧…

參考

系列文