跳转至正文

dart format 命令(用于格式化 Dart 代码的命令)

使用 dart format 命令可以根据 Dart 格式化指南 将你程序中多余的空格替换掉。这与你使用支持 Dart 的 IDE 或者编辑器格式化代码的效果相同。

指定要格式化的文件

#

请提供文件或目录的路径列表,来重新格式化一个或多个 Dart 文件。

指定一个路径

#

提供一个文件或目录的路径。如果指定一个目录,dart format 也会遍历其子目录。

**示例:**格式化当前目录下的所有 Dart 文件:

console
$ dart format .

指定多个路径

#

要指定多个文件或目录,请使用以空格符号分割的列表。

**示例:**下面的命令将会对 lib 目录中的所有 Dart 文件,以及一个 bin 目录下的 Dart 文件进行格式化。

console
$ dart format lib bin/updater.dart

防止 Dart 文件被覆写

#

默认情况下,dart format覆写 Dart 文件。

  • 不想覆写文件,请加上 --output-o 参数。

  • 要获取格式化文件的内容,请加上 -o show-o json

  • 只是查看哪些文件被更改,请加上 -o none

console
$ dart format -o show bin/my_app.dart

发生更改时发出通知

#

要让 dart format 在格式化发生更改时返回退出代码,请加上 --set-exit-if-changed 参数。

  • 如果发生更改,dart format 命令返回的退出代码为 1

  • 如果没有发生更改,dart format 命令返回的退出代码为 0

与持续集成 (CI) 系统一起使用退出代码,这样它们就可用根据退出代码来触发另一项操作。

console
$ dart format -o none --set-exit-if-changed bin/my_app.dart

What changes?

#

dart format makes the following formatting changes:

  • Removes whitespace.
  • Wraps every line to 80 characters long or shorter.
  • Adds trailing commas to any argument or parameter list that splits across multiple lines, and removes them from ones that don't.
  • Might move comments before or after a comma.

To learn more about best practices for writing and styling Dart code, check out the Dart style guide.

Configuring formatter page width

#

When you run dart format, the formatter defaults to 80 character line length or shorter. If you'd like to configure the line length for your project, you can add a top-level formatter section to the analysis_options.yaml file, like so:

analysis_options.yaml
yaml
formatter:
  page_width: 123

With the analysis options file typically at the root, the configured line length will apply to everything in the package.

You can also configure individual files' line length, overriding the analysis options file, with a marker comment at the top of the file before any other code:

dart
// dart format width=123

了解更多

#

请使用 dart help 命令,或查看 dart_style package 的文档,来了解其他命令行选项。

console
$ dart help format

如果想要了解格式化决策背后的更多信息,请查看 格式化常见问题