dart-write-documentation
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseWriting Dart API Documentation
编写Dart API文档
Contents
目录
- 1. Scope and Structure
- 2. Tone and Openers
- 3. Strict Anti-Patterns (Banned)
- 4. Technical Placement & Resolution
- 5. Linking and Markdown
- 6. Verification
- Examples
When asked to write or update documentation for Dart code, you must strictly follow these formatting rules based on the "Effective Dart: Documentation" guidelines.
当需要编写或更新Dart代码的文档时,必须严格遵循这些基于《Effective Dart: 文档规范》的格式规则。
1. Scope and Structure
1. 范围与结构
- Target Public APIs: Focus your documentation efforts on public declarations. Do not document private members (those starting with an underscore ) unless explicitly instructed, as they do not appear in generated API reference sites.
_ - Always use : Use
///consecutive line comments for all API documentation. Never use///block comments./** ... */ - Proper Sentences: Format all comments like proper sentences. Capitalize the first word (unless it's a lowercase identifier) and end with a period.
- The First Paragraph: The first paragraph of a doc comment must be a single, concise sentence that summarizes the element. End it with a period. Dartdoc extracts this verbatim for list views.
- Separation: Always separate the first sentence summary from the rest of the documentation with a blank line containing . Never output a completely empty newline (e.g., a
///without\n), as this terminates the doc comment block.///
- 面向公共API:将文档工作聚焦于公共声明。除非明确要求,否则不要为私有成员(以下划线开头的成员)编写文档,因为它们不会出现在生成的API参考站点中。
_ - 始终使用:所有API文档都使用连续行注释
///。切勿使用///块注释。/** ... */ - 规范句式:所有注释均需格式化为完整的句子。首词大写(除非是小写标识符),并以句号结尾。
- 第一段要求:文档注释的第一段必须是一个简洁的单句,概括该元素的功能,以句号结尾。Dartdoc会直接提取这段内容用于列表视图展示。
- 内容分隔:务必使用一行仅包含的空白行,将首句摘要与文档其余部分分隔开。切勿输出完全空的换行(例如不带
///的///),这会终止文档注释块。\n
2. Tone and Openers
2. 语气与开头
- Noun phrases for properties: Start descriptions of variables, getters, or setters with a noun phrase.
(Not "Gets the radius...")
/// The radius of the sphere. - "Whether" for booleans: Start documentation for boolean properties with "Whether".
/// Whether the connection is active. - Third-person verbs for methods: Start descriptions of methods or functions with a third-person verb that describes what it does.
(Not "Initialize" or "This method initializes").
/// Initializes the database. - Avoid redundancy: Do not restate the signature or the element name. Do not say "This class is a..." or "The foo method does...".
- 属性用名词短语:变量、getter或setter的描述需以名词短语开头。
(而非“获取半径...”)
/// The radius of the sphere. - 布尔属性用“Whether”:布尔属性的文档需以“Whether”开头。
/// Whether the connection is active. - 方法用第三人称动词:方法或函数的描述需以第三人称动词开头,说明其功能。
(而非“Initialize”或“此方法初始化”)
/// Initializes the database. - 避免冗余:不要重复签名或元素名称。不要使用“此类是一个...”或“foo方法用于...”这类表述。
3. Strict Anti-Patterns (Banned)
3. 严格禁止的反模式
- No Javadoc/TSDoc Tags (,
@param,@return, etc.): Never use Javadoc-style tags (@throws,@param,@return,@returns,@throws,@exception,@see). Instead, weave parameter names, return behavior, and exceptions into the prose.@type
- 禁止使用Javadoc/TSDoc标签(、
@param、@return等):切勿使用Javadoc风格的标签(@throws、@param、@return、@returns、@throws、@exception、@see)。应将参数名称、返回行为和异常信息融入正文描述中。@type
4. Technical Placement & Resolution
4. 技术放置与解析
- Annotations (, etc.): Doc comments must be placed before metadata annotations.
@override - Inherited Documentation: Avoid duplicating doc comments on members if the behavior does not differ from the superclass or interface. Dartdoc automatically inherits the base documentation.
@override - Getter/Setter Pairs: If a property has both a getter and a setter, place the documentation only on the getter. Tooling will emit a warning if both are documented.
- Default Constructors: To link to a default, unnamed constructor in doc comments, you must use the syntax (e.g.,
.new).[ClassName.new]
- 注解(等):文档注释必须放在元数据注解之前。
@override - 继承文档:如果成员的行为与父类或接口无差异,避免重复编写文档注释。Dartdoc会自动继承基础文档。
@override - Getter/Setter对:如果属性同时有getter和setter,仅在getter上放置文档注释。如果两者都添加文档,工具会发出警告。
- 默认构造函数:要在文档注释中链接到默认的无命名构造函数,必须使用语法(例如
.new)。[ClassName.new]
5. Linking and Markdown
5. 链接与Markdown格式
- Square brackets () for in-scope symbols: Use square brackets to link to any in-scope identifier (parameters, classes, methods, fields, and top-level functions) so dartdoc can resolve them. Never use backticks for parameters.
[identifier] - No parentheses in method links: Avoid parentheses in links (e.g., use , not
[String.contains]).[String.contains()] - Backticks for keywords & literals: Use backticks for keywords, literals, and arbitrary expressions (e.g. ,
`null`,`true`). Never put keywords in square brackets (avoid`void`or[null]).[true] - Out-of-Scope Links: If you need to link to a symbol that is not imported by the current library, use the directive at the top of the file (on the
@docImportdeclaration) rather than adding a standardlibrary;.import - Code Blocks: For code samples, always label the language fence. Use for Dart, or
```dartfor shell commands. Do not leave code blocks unlabelled, as Dartdoc will attempt to auto-detect the language and frequently guesses wrong.```sh - Formatting: Use standard Markdown (bold, lists, etc.) after the first paragraph to fully explain edge cases, exceptions thrown, and internal behavior the caller cannot see.
- 作用域内符号用方括号():使用方括号链接到任意作用域内的标识符(参数、类、方法、字段和顶层函数),以便dartdoc解析它们。切勿对参数使用反引号。
[identifier] - 方法链接中不要加括号:链接中避免使用括号(例如使用,而非
[String.contains])。[String.contains()] - 关键字与字面量用反引号:关键字、字面量和任意表达式使用反引号包裹(例如、
`null`、`true`)。切勿将关键字放在方括号中(避免`void`或[null])。[true] - 跨作用域链接:如果需要链接到当前库未导入的符号,请在文件顶部的声明上使用
library;指令,而非添加标准的@docImport语句。import - 代码块:代码示例必须标注语言围栏。Dart代码使用,shell命令使用
```dart。不要让代码块无标注,否则Dartdoc会尝试自动检测语言,且经常判断错误。```sh - 格式规范:首段之后使用标准Markdown格式(加粗、列表等),充分说明边缘情况、抛出的异常以及调用者无法看到的内部行为。
6. Verification
6. 验证
After writing or updating doc comments:
- Run to ensure all bracketed references resolve properly without triggering
dart analyzewarnings.comment_references - (Optional) Run to verify the generated documentation renders cleanly.
dart doc
编写或更新文档注释后:
- 运行确保所有方括号引用都能正确解析,不会触发
dart analyze警告。comment_references - (可选)运行验证生成的文档能否正常渲染。
dart doc
Examples
示例
1. Banned Tags vs. Prose
1. 禁用标签 vs 正文描述
Bad:
dart
/// This method fetches data.
/// @param force true to force reload.
/// @return the data
/// @throws NetworkException if host is unreachable.
Data load(bool force) { ... }Good:
dart
/// Fetches the remote data.
///
/// If [force] is true, this bypasses the local cache and forces a
/// network request.
///
/// Throws a [NetworkException] if the host is unreachable.
Data load(bool force) { ... }错误示例:
dart
/// This method fetches data.
/// @param force true to force reload.
/// @return the data
/// @throws NetworkException if host is unreachable.
Data load(bool force) { ... }正确示例:
dart
/// Fetches the remote data.
///
/// If [force] is true, this bypasses the local cache and forces a
/// network request.
///
/// Throws a [NetworkException] if the host is unreachable.
Data load(bool force) { ... }2. The Annotation Placement Trap
2. 注解放置陷阱
Bad:
dart
/// Renders the widget to the screen.
Widget build(BuildContext context) { ... }Good:
dart
/// Renders the widget to the screen.
Widget build(BuildContext context) { ... }错误示例:
dart
/// Renders the widget to the screen.
Widget build(BuildContext context) { ... }正确示例:
dart
/// Renders the widget to the screen.
Widget build(BuildContext context) { ... }3. Openers and Tone
3. 开头与语气
Bad:
dart
/// Gets if the connection is active.
bool get isActive => _active;
/// This method initializes the connection.
void init() { ... }Good:
dart
/// Whether the connection is active.
bool get isActive => _active;
/// Initializes the connection.
void init() { ... }错误示例:
dart
/// Gets if the connection is active.
bool get isActive => _active;
/// This method initializes the connection.
void init() { ... }正确示例:
dart
/// Whether the connection is active.
bool get isActive => _active;
/// Initializes the connection.
void init() { ... }4. Constructor Linking
4. 构造函数链接
Bad:
dart
/// Creates a new user. Similar to calling [User()].
User.create() { ... }Good:
dart
/// Creates a new user. Similar to calling [User.new].
User.create() { ... }错误示例:
dart
/// Creates a new user. Similar to calling [User()].
User.create() { ... }正确示例:
dart
/// Creates a new user. Similar to calling [User.new].
User.create() { ... }5. Out-of-Scope Links (@docImport)
5. 跨作用域链接(@docImport)
Bad:
dart
import 'package:http/http.dart'; // Adds unnecessary runtime dependency just for docs
/// To use this, you must pass a [Client].Good:
dart
/// @docImport 'package:http/http.dart';
library;
/// To use this, you must pass a [Client].错误示例:
dart
import 'package:http/http.dart'; // Adds unnecessary runtime dependency just for docs
/// To use this, you must pass a [Client].正确示例:
dart
/// @docImport 'package:http/http.dart';
library;
/// To use this, you must pass a [Client].