返回介绍

Code formatting

发布于 2019-12-09 21:31:32 字数 3162 浏览 865 评论 0 收藏 0

While your code may follow any preferred style—in our experience—teams of developers may find it more productive to:

  • Have a single, shared style, and
  • Enforce this style through automatic formatting.

The alternative is often tiring formatting debates during code reviews, where time may be better spent on code behavior rather than code style.

Automatically formatting code in Android Studio and IntelliJ

Install the Dart plugin (see Editor setup) to get automatic formatting of code in Android Studio and IntelliJ.

To automatically format the code in the current source code window, right-click in the code window and select Reformat Code with dartfmt. You can add a keyboard shortcut to this in Keymap section of IntelliJ Preferences.

Automatically formatting code in VS Code

Install the Flutter extension (see Editor setup) to get automatic formatting of code in VS Code.

To automatically format the code in the current source code window, right-click in the code window and select Format Document. You can add a keyboard shortcut to this VS Code Preferences.

To automatically format code whenever you save a file, set the editor.formatOnSave setting to true.

Automatically formatting code with the ‘flutter’ command

You can also automatically format code in the command line interface (CLI) using the flutter format command:

$ flutter format path1 path2 ...

Using trailing commas

Flutter code often involves building fairly deep tree-shaped data structures, for example in a build method. To get good automatic formatting, we recommend you adopt the optional trailing commas. The guideline for adding a trailing comma is simple: Always add a trailing comma at the end of a parameter list in functions, methods, and constructors where you care about keeping the formatting you crafted. This helps the automatic formatter to insert an appropriate amount of line breaks for Flutter-style code.

Here is an example of automatically formatted code with trailing commas:

Automatically formatted code with trailing commas

And the same code automatically formatted code without trailing commas:

Automatically formatted code without trailing commas

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文