目次

自明なローカル変数の型を省略

ローカル変数の自明な型注釈を省略します。

このルールは現在実験段階であり、安定版SDKではまだ利用できません。

このルールには、クイック修正が利用可能です。

互換性のないルール: always_specify_types

詳細

#

型が明らかな場合は、初期化されたローカル変数に型注釈を付けないでください。

ローカル変数、特に関数が小さくなる傾向がある最近のコードでは、スコープが非常に小さくなっています。型を省略することで、読者の注意は、より重要な変数の*名前*とその初期値に集中します。したがって、明らかなローカル変数の型注釈は省略する必要があります。

悪い例

dart
List<List<Ingredient>> possibleDesserts(Set<Ingredient> pantry) {
  List<List<Ingredient>> desserts = <List<Ingredient>>[];
  for (final List<Ingredient> recipe in cookbook) {
    if (pantry.containsAll(recipe)) {
      desserts.add(recipe);
    }
  }

  return desserts;
}

const cookbook = <List<Ingredient>>[....];

良い例

dart
List<List<Ingredient>> possibleDesserts(Set<Ingredient> pantry) {
  var desserts = <List<Ingredient>>[];
  for (final List<Ingredient> recipe in cookbook) {
    if (pantry.containsAll(recipe)) {
      desserts.add(recipe);
    }
  }

  return desserts;
}

const cookbook = <List<Ingredient>>[....];

推論された型が、変数に持たせたい型ではない場合があります。たとえば、後で他の型の値を代入する予定があるかもしれません。また、初期化式の型が自明ではなく、この型を文書化することが将来のコードの読者にとって役立つため、明示的に型注釈を作成したい場合もあるでしょう。あるいは、依存関係(近くのコード、インポート、あらゆる場所)の将来の更新によって、その変数の型が警告なしに変更され、この変数が使用されている場所でコンパイル時エラーまたは実行時バグが発生しないように、特定の型にコミットしたい場合もあるでしょう。このような場合は、変数に目的の型注釈を付けてください。

良い例

dart
Widget build(BuildContext context) {
  Widget result = someGenericFunction(42) ?? Text('You won!');
  if (applyPadding) {
    result = Padding(padding: EdgeInsets.all(8.0), child: result);
  }
  return result;
}

このルールは実験段階です。 評価中で、変更または削除される可能性があります。動作に関するフィードバックをお待ちしています!主な問題は次のとおりです。https://github.com/dart-lang/linter/issues/3480.

使用方法

#

omit_obvious_local_variable_typesルールを有効にするには、analysis_options.yamlファイルのlinter > rulesの下にomit_obvious_local_variable_typesを追加します。

analysis_options.yaml
yaml
linter:
  rules:
    - omit_obvious_local_variable_types