flutter代码规范配置

749 阅读1分钟

背景

 学习新的语法时,经常会习惯性带上以前使用的语法风格,导致新的语法不规范,为了能够编写出更加健壮的flutter代码,谷歌在SDK2.3.0开始出了flutter代码规范检查,方便我们在开发时及时发现我们代码问题。如果你创建项目时使用的SDK是2.3.0以上默认是配置代码规范的,我现在说下2.3.0以下怎么配置代码规范。

分析简述

image.png

常见的代码规范

image.png 更详情的可以查看dart团队代码规范明细

使用插件检测代码规范

集成代码检查库

配置1:检查你的SDK是否高于2.3.0,没有就更新高版本sdk

image.png

配置2:在项目根目录创建analysis_options.yaml文件 (文件内容如下)

# This file configures the analyzer, which statically analyzes Dart code to
# check for errors, warnings, and lints.
#
# The issues identified by the analyzer are surfaced in the UI of Dart-enabled
# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be
# invoked from the command line by running `flutter analyze`.

# The following line activates a set of recommended lints for Flutter apps,
# packages, and plugins designed to encourage good coding practices.
include: package:flutter_lints/flutter.yaml

linter:
  # The lint rules applied to this project can be customized in the
  # section below to disable rules from the `package:flutter_lints/flutter.yaml`
  # included above or to enable additional rules. A list of all available lints
  # and their documentation is published at
  # https://dart-lang.github.io/linter/lints/index.html.
  #
  # Instead of disabling a lint rule for the entire project in the
  # section below, it can also be suppressed for a single line of code
  # or a specific dart file by using the `// ignore: name_of_lint` and
  # `// ignore_for_file: name_of_lint` syntax on the line or in the file
  # producing the lint.
  rules:
    # avoid_print: false  # Uncomment to disable the `avoid_print` rule
    # prefer_single_quotes: true  # Uncomment to enable the `prefer_single_quotes` rule

# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options

如下图

image.png

配置3:配置依赖 是在dev_dependencies配置(注意pub get)

image.png

效果:

image.png

flutter_lints库有两个文件

image.png

 删除规则

同样也可以删除默认的规则中的某些规则,或者让他不起效,只需要在analysis_option.yaml文件中的rules中,增加规则名称,并设置为false (注意pub get)

在analysis_options文件

image.png

image.png

增加规则

同样也可以新增规则,只需要在analysis_option.yaml文件中的rules中,增加规则名称,并设置为true (注意pub get)

image.png

效果如下

image.png

 执行flutter analyze命令来检测你的代码

参考

官网:pub.flutter-io.cn/documentati…

           dart-lang.github.io/linter/lint…

闲鱼:mp.weixin.qq.com/s/Xsp4pdxqd…