每次都被const
的提示烦的不行,有时候还因为加上了const
导致报错,以往在idea
关闭提示都是去settings
关闭,但第一次用Android Studio
实在不知道去哪关。
后来知道项目根目录下有个文件analysis_options.yaml
,添加一行配置 prefer_const_constructors: false
就不提示了。
完整代码:
# 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:
prefer_const_constructors: false
# 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
请注意,要使配置文件生效,你可能需要重新启动编辑器,来重新加载 Analyzer 的配置。
但其实,我还是建议手动加上const
,可以使用Andorid Studio
里提示添加const
那里,选择一键添加所有const
,这么做的原因是:
-
性能优化:使用const可以在编译时进行计算,并在运行时重用相同的对象。这可以减少内存使用和提高应用程序的性能。当使用const创建的对象在多个地方被引用时,只会创建一个实例,并在需要时共享它。
-
预防错误:使用const可以防止意外的对象更改。一旦使用const创建的对象被赋值给一个变量,该变量将无法更改其引用的对象。这有助于避免在代码中意外修改对象,提高代码的可靠性和可维护性。
-
常量传递:const可以用于函数参数、构造函数和方法调用中。它使得可以在编译时确定参数值,从而优化代码并减少运行时的计算。
-
编译时错误检测:使用const可以在编译时捕获一些错误,例如无效的表达式或不可用的操作。这有助于提前发现问题并减少运行时错误。
其他知识点:
analysis_options.yaml 文件是用于配置 Dart 代码分析器(Analyzer)的配置文件。Analyzer 是 Dart 开发工具链中的一部分,用于静态分析代码并提供代码质量建议、警告和错误。
通过 analysis_options.yaml 文件,可以自定义 Analyzer 的行为,包括选择性地启用或禁用某些规则、调整警告级别、配置代码风格规范等。一般来说,这个文件位于项目的根目录下。
具体配置是:
- analyzer:用于配置 Analyzer 的规则和行为。
linter:用于配置 Linter 规则,Linter 是 Dart 代码风格检查工具。 - dart2js:用于配置 Dart 到 JavaScript 编译器的规则。
- dart_style:用于配置 Dart 代码格式化工具的规则。
因此,我们可以在 analysis_options.yaml 文件中添加或修改这些选项的值来满足项目需求。例如,我们可以启用严格的代码风格检查、禁用某些警告或错误、配置命名约定等。
使用 analysis_options.yaml 文件可以帮助我们在开发过程中保持代码质量和一致性,并提供有关代码改进的建议。它可以用于个人项目或团队项目,以确保代码在质量和风格上符合预期。