代码检测是规范写法,提高质量的一种重要方案,几乎所有的主流语言都有相关方案。在Flutter开发过程中,我们可以使用IDE自带的Inspect Code功能,也可以直接使用命令行dart analyze
官方方案
Flutter官方提供analyzer来检测代码
使用步骤
- pubspec.yaml配置
1 2 3 4 5 6
| dev_dependencies: lint: flutter_lints: ^1.0.0
|
- 新建analysis_options.yaml配置文件,放在项目的根目录。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
include: package:lints/recommended.yaml
analyzer: exclude: - [build/**] - lib/*.g.dart language: strict-casts: true strict-inference: true strict-raw-types: true errors: invalide_assignment: warning missing_return: error dead_code: info strong-mode: implicit-casts: false
linter: rules: - cancel_subscriptions
|
- 执行命令
1 2 3
| # 分析项目命令 # 分析从根目录开始遍历,发现analysis_options.yaml配置文件,则执行自定义静态代码分析,若没有则默认配置(https://github.com/flutter/flutter/blob/master/analysis_options.yaml) dart analyze
|
自定义规则
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| include: package:flutter_lints/flutter.yaml
analyzer: exclude: - [build/**] - lib/*.g.dart - build/** language: strict-casts: true strict-raw-types: true errors: always_declare_return_types: warning null_closures: warning invalide_assignment: warning missing_return: error unnecessary_statements: warning prefer_typing_uninitialized_variables: warning dead_code: info prefer_interpolation_to_compose_strings: ignore use_key_in_widget_constructors: error control_flow_in_finally: error no_logic_in_create_state: error hash_and_equals: error unrelated_type_equality_checks: error always_use_package_imports: error avoid_print: error use_build_context_synchronously: error strong-mode: implicit-casts: false
linter: rules: cancel_subscriptions: true avoid_shadowing_type_parameters: false
|
使用sonarqube
https://betterprogramming.pub/flutter-and-sonarqube-for-static-code-analysis-51368a85c51c
安装sonarqube后台服务
本地安装sonar-scanner工具
本地项目配置
参考