LoginSignup
12
1

【Flutter】custom_lint:セットアップ

Posted at

はじめに

Flutterでレビュー負担軽減のためにcustom_lintを用いて自作のlintルールを設定しました。
手順等忘れないため記録として残します。

また、ルール別に記事を書くのでここでは目次+セットアップの紹介としたいと思います。

設定したlintルール一覧

  • buildメソッド内部でref.readを用いるのは避けよう
  • enumはifではなくswitchを用いよう
  • ifのネストは2階層までにしよう
  • nullabelの変数に対するアンラップは避けよう

セットアップ

1. ディレクトリの用意

lint用にディレクトリを用意します。
プロジェクト直下に以下のようなディレクトリ構造を用意してください。

└─ packages/my_custom_lint/
  ├─ lib/
  │  ├─ my_custom_lint.dart
     // この下は任意です
  │  ├─ if_nesting_limit.dart
  │  ├─ no_ref_read_variable_declaration_in_build_.dart
  │  ├─ nullable_unwrap_warning.dart
  │  └─ prefer_switch_over_if_with_enum.dart
  ├─ pubspec.lock
  └─ pubspec.yaml

2. 必要な設定

my_custom_lintとしている箇所は同じ名前で統一するようにしてください。

pubspec.yamlにはlint設定に必要なパッケージを記載します。
記載したら一度flutter pub getをしておいてください。

packages/my_custom_lint/pubspec.yaml
name: my_custom_lint
environment:
  sdk: ">=3.0.0 <4.0.0"

dependencies:
  analyzer: ^6.2.0
  analyzer_plugin: ^0.11.3
  custom_lint_builder: ^0.6.1
packages/my_custom_lint/my_custom_lint.dart
import 'package:custom_lint_builder/custom_lint_builder.dart';
import 'package:my_custom_lint/if_nesting_limit.dart';
import 'package:my_custom_lint/no_ref_read_variable_declaration_in_build_method.dart';
import 'package:my_custom_lint/prefer_switch_over_if_with_enum.dart';

PluginBase createPlugin() => _MyCustomLinter();

class _MyCustomLinter extends PluginBase {
  @override
  List<LintRule> getLintRules(CustomLintConfigs configs) => [
        // 各lintルールを定義したクラスを配置していく
        const NoRefReadVariableDeclarationInBuildMethod(),
        const PreferSwitchOverIfWithEnum(),
        const IfNestingLimit(),
        const NullableUnwrapWarning(),
      ];
}

次に、プロジェクト直下のpubspec.yamlに上記のlint用パッケージを追加します。
custom_lintパッケージと同時に以下のように定義してください。

pubspec.yaml
dev_dependencies:
  custom_lint: ^0.6.0
  my_custom_lint:
    path: packages/my_custom_lint

あとはflutter pub getをすれば適応が完了します。若干リロードに時差があるかもしれないのでうまく読みこまれない場合はlintの書き方の見直しやIDEの再起動をしてみてください。

12
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
1