dart-effective-style
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesedart-style-guide
Dart风格指南
Goal
目标
Applies idiomatic Dart styling, naming conventions, and formatting rules to ensure consistent, readable, and maintainable code across Dart and Flutter projects. Assumes a standard Dart SDK environment where the CLI is available.
dart在Dart和Flutter项目中应用符合语言习惯的Dart风格、命名规范及格式化规则,确保代码一致、可读且易于维护。本文假设你已拥有标准Dart SDK环境,且 CLI可用。
dartInstructions
操作步骤
-
Apply Naming Conventions Ensure all identifiers match Dart's official style guidelines. Use the Decision Logic section below to determine the correct casing for any given identifier.
-
Order Directives Organize all imports and exports at the top of the file in the following strict order, separated by blank lines, and sorted alphabetically within each group:
- imports.
dart: - imports.
package: - Relative imports.
- directives.
export
dartimport 'dart:async'; import 'dart:collection'; import 'package:bar/bar.dart'; import 'package:foo/foo.dart'; import 'util.dart'; export 'src/error.dart'; -
Format Code Always format the code using the official Dart formatter. If the formatter produces hard-to-read code, refactor the code (e.g., extract variables) to be more formatter-friendly.bash
dart format . -
Enforce Flow Control Braces Always use curly braces for flow control statements to prevent the dangling else problem.dart
// GOOD if (isWeekDay) { print('Bike to work!'); } else { print('Go dancing or read a book!'); } // ACCEPTABLE (Single line, no else) if (arg == null) return defaultValue; -
Handle Unused Callback Parameters Use wildcards () for unused callback parameters to signal intent.
_dartfutureOfVoid.then((_) { print('Operation complete.'); }); // Multiple unused parameters .onError((_, __) { print('Operation failed.'); });
-
遵循命名规范 确保所有标识符符合Dart官方风格指南。可参考下方的决策逻辑部分,确定任意标识符的正确大小写格式。
-
指令排序 将所有导入与导出指令整理在文件顶部,并严格按照以下顺序排列,各组之间用空行分隔,组内按字母顺序排序:
- 导入
dart: - 导入
package: - 相对路径导入
- 指令
export
dartimport 'dart:async'; import 'dart:collection'; import 'package:bar/bar.dart'; import 'package:foo/foo.dart'; import 'util.dart'; export 'src/error.dart'; -
代码格式化 始终使用官方Dart格式化工具格式化代码。如果格式化后的代码可读性变差,请重构代码(例如提取变量),使其更适配格式化工具。bash
dart format . -
强制使用流控制大括号 流控制语句必须使用大括号,以避免悬空else问题。dart
// 规范写法 if (isWeekDay) { print('Bike to work!'); } else { print('Go dancing or read a book!'); } // 可接受写法(单行且无else分支) if (arg == null) return defaultValue; -
处理未使用的回调参数 对于未使用的回调参数,使用通配符来明确表达意图。
_dartfutureOfVoid.then((_) { print('Operation complete.'); }); // 多个未使用参数 .onError((_, __) { print('Operation failed.'); });
Decision Logic
决策逻辑
When creating or renaming an identifier, follow this flowchart logic:
- Is it a Class, Enum, Typedef, Extension, or Type Parameter?
- Yes: Use .
UpperCamelCasedartclass SliderMenu {} typedef Predicate<T> = bool Function(T value); extension SmartIterable<T> on Iterable<T> {}
- Yes: Use
- Is it a Package, Directory, Source File, or Import Prefix?
- Yes: Use .
lowercase_with_underscoresdartimport 'dart:math' as math; import 'package:js/js.dart' as js; // File: slider_menu.dart
- Yes: Use
- Is it a Constant Variable or Enum Value?
- Yes: Use (Do NOT use
lowerCamelCaseunless matching legacy code).SCREAMING_CAPSdartconst pi = 3.14; const defaultTimeout = 1000;
- Yes: Use
- Is it a Variable, Parameter, Named Parameter, Class Member, or Top-Level Definition?
- Yes: Use .
lowerCamelCasedartvar count = 3; HttpRequest httpRequest;
- Yes: Use
- Does the name contain an Acronym or Abbreviation?
- Is it longer than two letters? Capitalize it like a normal word (e.g., ,
Http).Uri - Is it exactly two letters? Keep both capitalized (e.g., ,
ID) unless it is the start of aTVidentifier, in which case both are lowercase (e.g.,lowerCamelCase,idToken).tvSet
- Is it longer than two letters? Capitalize it like a normal word (e.g.,
- Is the member or top-level declaration meant to be private to its library?
- Yes: Prefix it with a leading underscore .
_ - No: Do NOT use a leading underscore. (Never use leading underscores for local variables or parameters).
- Yes: Prefix it with a leading underscore
创建或重命名标识符时,请遵循以下流程逻辑:
- 是否为类、枚举、类型定义、扩展或类型参数?
- 是: 使用格式。
UpperCamelCasedartclass SliderMenu {} typedef Predicate<T> = bool Function(T value); extension SmartIterable<T> on Iterable<T> {}
- 是: 使用
- 是否为包、目录、源文件或导入前缀?
- 是: 使用格式。
lowercase_with_underscoresdartimport 'dart:math' as math; import 'package:js/js.dart' as js; // 文件: slider_menu.dart
- 是: 使用
- 是否为常量变量或枚举值?
- 是: 使用格式(除非适配遗留代码,否则请勿使用
lowerCamelCase格式)。SCREAMING_CAPSdartconst pi = 3.14; const defaultTimeout = 1000;
- 是: 使用
- 是否为变量、参数、命名参数、类成员或顶层定义?
- 是: 使用格式。
lowerCamelCasedartvar count = 3; HttpRequest httpRequest;
- 是: 使用
- 名称中是否包含首字母缩写或缩写词?
- 长度超过两个字母? 像普通单词一样大写首字母(例如、
Http)。Uri - 恰好两个字母? 两个字母都大写(例如、
ID),除非它是TV标识符的开头,此时两个字母都小写(例如lowerCamelCase、idToken)。tvSet
- 长度超过两个字母? 像普通单词一样大写首字母(例如
- 成员或顶层声明是否仅对其所在库可见(私有)?
- 是: 在名称前添加下划线前缀。
_ - 否: 请勿添加下划线前缀。(局部变量或参数绝不能使用下划线前缀)。
- 是: 在名称前添加下划线
Constraints
约束条件
- Mandatory Formatting: DO run as a mandatory step before committing or finalizing any code changes.
dart format - Import Preferences: PREFER relative imports for files located inside the directory of the same package.
lib - No Prefix Letters: DON'T use prefix letters (like Hungarian notation). Use , not
defaultTimeout.kDefaultTimeout - No Explicit Library Names: DON'T explicitly name libraries (e.g., avoid ). Use
library my_library;if a directive is needed for annotations.library; - Line Length: PREFER lines 80 characters or fewer. STOP AND ASK THE USER: if a specific string or configuration requires exceeding the 80-character limit and cannot be reasonably refactored.
- Related Skills: ,
dart-static-analysis.dart-api-design
- 强制格式化: 在提交或完成任何代码变更前,必须执行命令。
dart format - 导入偏好: 对于同一包内目录下的文件,优先使用相对路径导入。
lib - 禁止前缀字母: 请勿使用前缀字母(如匈牙利命名法)。应使用而非
defaultTimeout。kDefaultTimeout - 禁止显式库名: 请勿显式命名库(例如避免使用)。如果注解需要库指令,请使用
library my_library;。library; - 行长度: 每行长度建议不超过80个字符。若特定字符串或配置需要超过80字符限制且无法合理重构,请暂停并询问用户。
- 相关技能: ,
dart-static-analysis.dart-api-design