docs

TOP(About this memo)) > 一覧(Dart) > 宣言

宣言

var, final, const

void main() {
  const test = "333";
  //test = "444"; // error
  print(test);
  
  final test2 = "444";
  //test2 = "444"; // error
  print(test2);
  
  var test3 = "555";
  test3 = "556";
  print(test3);
  
  //var test4 = const "666"; //error. 既にconstである値にconstをつけることはできない?
  
  var constantList = const [1,2];
  // constantList[1] = 1; // error
  // constantList.add(1); // error
  constantList = [1,2,3];
  print(constantList);// [1,2,3]
}
class A {
  A(this._test);
  int _test;
}
void main() {
  final aa = A(4);
  aa._test = 100;// finalで宣言した場合でもオブジェクトの中身の変更は可能。
  //const aaa = const A(5);// Aは定数constructorではないためcompile error.
}
void main() {
  const b = B(3);// 定数constructorのためconstとして作成できる。
  var bb = B(3);// constと書かなくてもconst扱いになる。
  var bbb = const B(3); // varで宣言しても右辺がconstならconst
  final bbbb = B(4);// finalで宣言してもconst扱いになっているはず。
}

class B {
  const B(this.test);
  final int test;
}

constの省略

const pointAndLine = const {
  'point': const [const ImmutablePoint(0, 0)],
  'line': const [const ImmutablePoint(1, 10), const ImmutablePoint(-2, 11)],
};
const pointAndLine = {
  'point': [ImmutablePoint(0, 0)],
  'line': [ImmutablePoint(1, 10), ImmutablePoint(-2, 11)],
};

(参考)関数リテラルはconstではない

void example1() {
  // const Function bar = () {}; // error.
  const Function bar = a; // ok.
}
void a() {} // トップレベルの関数はconstとなる

This is because all functions in dart inherit Function class which doesn’t have const constructor.

関連:Constant function literals

(参考)引数のデフォルト値のconstは省略ができない。

late

Future<String> fetch(Future<(String, int)> Function() f) async {
    late (String, int) result;
    // int result; // lateを使わない場合は return文で未初期化としてエラーになる。
    try {
      result = await f();
    } catch (e) {
      // ...
    }
    // ...
    return result.$1;
}