トッカンソフトウェア

Dart 基本

Dartの基本をやります。


変数宣言、for文、if文、switch文

lib\main.dart


void main() {
  int cnt = 3;
  double dbl = 1.23;
  String str = 'Hello';
  bool boo = true;

  List<int> ary = [];
  Set<String> names = {};
  Map<String, String> map = {};


  for (int i = 0; i < cnt; i++) {
    if (i == 0) {
      print(str);
      boo = true;
    } else if (boo) {
      print(dbl);
      boo = false;
    } else {
      print(i);
    }

    switch (i) {
      case 0:
        print("world");
        break;
      default:
        print("-");
        break;
    }
  }
}

実行結果


Hello
world
1.23
-
2
-


List

lib\main.dart


void main() {
  List<String> ary = ["one", "two", "three"];

  ary[0] = "ONE";
  ary.add("four");
  ary.insert(1, "X");
  ary.remove("two");

  ary.forEach((val) {
    print(val);
  });

  print(ary.length);
  print(ary.contains("ONE"));
  print(ary.indexOf("ONE"));

  ary.sort();

  for (String val in ary) {
    print(val);
  }
}

実行結果


ONE
X
three
four
4
true
0
ONE
X
four
three


Set


void main() {
  Set<String> ary = {"one", "two", "three"};

  ary.add("four");
  ary.remove("two");

  ary.forEach((val) {
    print(val);
  });

  print(ary.length);
  print(ary.contains("four"));


  for (String val in ary) {
    print(val);
  }
}

実行結果


one
three
four
3
true
one
three
four

Map


void main() {
  Map<String, String> map1 = {'a1': 'b1', 'a2': 'b2'};

  map1['a2'] = 'B2';
  map1['a3'] = 'b3';

  print(map1.containsKey('a1'));
  print(map1.containsValue('b1'));

  map1.forEach((key, value) {
    print(key + "-" + value);
  });

  for (String key in map1.keys) {
    String str = map1[key] ?? 'no data';
    print(key + "+" + str);
  }
}

実行結果


true
true
a1-b1
a2-B2
a3-b3
a1+b1
a2+B2
a3+b3


関数


void main() {
  test();
}

void test() {
  print(plus(1, 2));
  print(plusNamed(a: 1, b: 2, c: 3));
  print(plusOptional(1, 2, 3));
}

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

int plusNamed({required int a, int b = 0, int? c}) {
  if (c != null) {
    return a + b + c;
  }
  return a + b;
}

int plusOptional(int a, [int b = 0, int? c]) {
  if (c != null) {
    return a + b + c;
  }
  return a + b;
}

実行結果


3
6
6



ページのトップへ戻る