Open2

[Dart] Tips Memo

にしにし

初期化について

参考

https://dart.dev/language/variables

変数の初期化は必ず宣言時である必要はなく、利用時までに初期化されていれば良い。
コンパイラ側で確実に初期化されると判断されれば、finalで宣言しても良い。

void main() {
  final splitLengths = 'hoge hoge hoge'.split(' ').length;
  final String word;  // varを使わなくても良い

  if(splitLengths == 3){
    word = 'hello';
  } else {
    word = 'world';
  }

  print(word);
}

late(遅延初期化)について

コンパイラ側で初期化されるかを判断できない場合がある。(グローバル変数の宣言など)
その場合は、lateを使うことによってコンパイルエラーを回避する事ができる。
ただし、利用時に正しく初期化されていないとランタイムエラーが発生する

late final String description;

void main() {
  description = 'Feijoada!';
  print(description);
}

Tips
lateをマークしながら、宣言時に初期化をしておくと、利用時に初めて初期化処理が実行される。
使用される頻度が少ないケースや初期化の処理が重い場合に有効。

late String temperature = readThermometer(); // Lazily initialized.

クラスでのlateキーワードの使用イメージ

class Person {
  final String firstName;
  final String lastName;
  
  // Using 'late' to delay initialization until 'fullName' is accessed
  late final String fullName = _generateFullName();

  Person(this.firstName, this.lastName);

  String _generateFullName() {
    // Accessing 'this' to combine first and last names
    return '${this.firstName} ${this.lastName}';
  }
}

void main() {
  var person = Person('John', 'Doe');
  print(person.fullName); // Output: John Doe
}
にしにし

コメントについて

参考

https://dart.dev/language/comments

3種類の記述方法がある

Single-line comments

1行の場合は//を用いてファイル内でコメントできる。

void main() {
  // TODO: refactor into an AbstractLlamaGreetingFactory?
  print('Welcome to my Llama farm!');
}

Multi-line comments

複数行でまとめたい場合は/**/を用いてファイル内でコメントできる。

void main() {
  /*
   * This is a lot of work. Consider raising chickens.

  Llama larry = Llama();
  larry.feed();
  larry.exercise();
  larry.clean();
   */
}

Documentation comments

コメント内でフィールドやメソッド、関数やパラメータを[]で囲むと各自ジャンプする事ができる。(生成したドキュメント内でも参照できる)

/// A domesticated South American camelid (Lama glama).
///
/// Andean cultures have used llamas as meat and pack
/// animals since pre-Hispanic times.
///
/// Just like any other animal, llamas need to eat,
/// so don't forget to [feed] them some [Food].
class Llama {
  String? name;

  /// Feeds your llama [food].
  ///
  /// The typical llama eats one bale of hay per week.
  void feed(Food food) {
    // ...
  }

  /// Exercises your llama with an [activity] for
  /// [timeLimit] minutes.
  void exercise(Activity activity, int timeLimit) {
    // ...
  }
}

キュメントを作成は、Dart's documentation generation toolを用いてドキュメントを作成する事ができる。

https://dart.dev/tools/dart-doc
https://dart.dev/effective-dart/documentation