docs

TOP(About this memo)) > 一覧(Dart) > 文法

前置、後置

void main() {
  int a = 0;
  print(a++);//0
  print(++a);//2
}

comments

文(statement)

式(expression)

control statement

label

オペレーター

Bitwise and shift operators

assignment-operators

spread operator(スプレッド演算子)

var arrayInt = [1, 2, 3];
var arrayString = ['a', 'b', 'c'];
var addArray = [...arrayInt, ...arrayString];
print(addArray); // [1, 2, 3, a, b, c]

カスケード(Cascade notation)

List<String> test = ['a'];
test.add('b');
test.add('c');
// 上記は以下のように書くことができる
List<String> test = ['a']..add('b')..add('c');

算術演算子

assert(2 + 3 == 5);
assert(2 - 3 == -1);
assert(2 * 3 == 6);
assert(5 / 2 == 2.5); // Result is a double
assert(5 ~/ 2 == 2); // Result is an int
assert(5 % 2 == 1); // Remainder
assert('5/2 = ${5 ~/ 2} r ${5 % 2}' == '5/2 = 2 r 1');

pattern, switch, if-case(WIP)

Dart3のswitch

enum Test{
  a,
  b,
  c
}
void main() {
  Test t = Test.a;
  
  switch(t) {
      case Test.a:
      case Test.b:
      case Test.c:
        print("1");
  }
  
  switch(t) {
      case Test.a:
        print("2-a");
      case Test.b:
        print("2-b");
      case Test.c:
        print("2-c");
  }
  
  switch(t) {
      case Test.a || Test.b || Test.c:
        print("3");
  }
}
// 1
// 2-a
// 3

(参考) enum以外にswitch構文を使ってみる

int compare(int a, int b) {
  return switch ((a, b)) {
    (int c1, int c2) when c1 == c2 => -1,
    (int c1, int c2) when c1 > c2 => 0,
    (int c1, int c2) when c1 < c2 => -1,
    (_, _) => throw "unexpected" // (_, _)を入れないとエラー
  };
}

int compare2(int a, int b) {
  switch ((a, b)) {
    case (int c1, int c2) when c1 == c2:
      return 0;
    case (int c1, int c2) when c1 > c2:
      return 1;
    case (int c1, int c2) when c1 < c2:
      return -1;
    default:
      throw "unexpected"; // defaultを入れないとエラー
  }
}

// 以下より抜粋
// https://api.flutter.dev/flutter/widgets/Overlay-class.html
final (String label, Color? color) = switch (currentPageIndex) {
  0 => ('Explore page', Colors.red),
  1 => ('Commute page', Colors.green),
  2 => ('Saved page', Colors.orange),
  _ => ('No page selected.', null),
};