無腦玩了一下 Flutter, 後來還是覺得要看一下 Dart 語言基本用法, 這篇單純紀錄一下,最近會補完自己覺得該備忘的範例

Install

brew tap dart-lang/dart
brew install dart

Variables

int, double, bool, String, list, map

const - 常數,賦值後不可變更,必須明確賦值

final - 常數,賦值後不可變更,可以是運算後過的結果

var firstname = "Bob";
var year = 1989;
String lastName = "Lu";

const bar = 1000000;
final String name = 'Bob';

Control flow statements

if (a > 1) {
  // ...
} else if (a > 2) {
  // ...
}

switch (expression) {
  case 'what':
    // ...
    break;
  case 'does':
    // ...
    break;
  case 'the':
    // ...
    break;
  case 'fox':
    // ...
    break;
  case 'say':
    // ...
    break;
  default:
  // ...
}

for (var i in data) {
  print(i);
}

for(int i = 1; i < 5; i++) {
  print(i);
}

while (i < 2019) {
  i++;
}

// break, continue, return

Function

int sum(int a, int b){
  return a + b
}

void printSomething(){
  print("something");
}

Class

class Animal{
  // ...
}

class Dog extends Animal{
  String name;
  int age;

  // contrunctor
  Dog(this.name, this.age) {}

  // method
  void sayHi() {
    print(name + "(" + age.toString() + "): ");
    if (age > 1) {
      print("ding ding ding ding ding");
    } else {
      print('woof');
    }
  }
}


var myDog = Dog('Jex', 1);
myDog.sayHi();
var yourDog = Dog('Jack', 2);
yourDog.sayHi();

Mixin

abstract class Walker {}
abstract class Flyer {}

class Animal{}
class Dog extends Animal with Walker {}
class Bird extends Animal with Walker, Flyer {}

Interfaces

只繼承原class的API,不繼承原class的實作

class Camera {
  void takePhoto() {
    // 這邊不會被Phone繼承實作
  }
}

class Phone implements Camera {
  void takePhoto() {
    print("takePhoto from Phone");
  }
}

Future, async, await

Future<void> printWithDelay(String message) async {
  await Future.delayed(Duration(seconds: 1));
  print(message);
}

Future<void> printWithDelay(String message) {
  return Future.delayed(Duration(seconds: 1)).then((_) {
    print(message);
  });
}
Future<void> printWithDelay() {
  return Future.delayed(new Duration(seconds: 2)).then((_) {
    print("execute printWithDelay");
  });
}

print("before printWithDelay");
printWithDelay();
print("after printWithDelay");

// before printWithDelay
// after printWithDelay
// execute printWithDelay

Reference:

https://dart.dev/samples