dart-write-documentation

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Writing Dart API Documentation

编写Dart API文档

Contents

目录

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
    \n
    without
    ///
    ), 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.
    /// The radius of the sphere.
    (Not "Gets the radius...")
  • "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.
    /// Initializes the database.
    (Not "Initialize" or "This method initializes").
  • 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.
  • 方法用第三人称动词:方法或函数的描述需以第三人称动词开头,说明其功能。
    /// Initializes the database.
    (而非“Initialize”或“此方法初始化”)
  • 避免冗余:不要重复签名或元素名称。不要使用“此类是一个...”或“foo方法用于...”这类表述。

3. Strict Anti-Patterns (Banned)

3. 严格禁止的反模式

  • No Javadoc/TSDoc Tags (
    @param
    ,
    @return
    ,
    @throws
    , etc.):
    Never use Javadoc-style tags (
    @param
    ,
    @return
    ,
    @returns
    ,
    @throws
    ,
    @exception
    ,
    @see
    ,
    @type
    ). Instead, weave parameter names, return behavior, and exceptions into the prose.
  • 禁止使用Javadoc/TSDoc标签(
    @param
    、
    @return
    、
    @throws
    等)
    :切勿使用Javadoc风格的标签(
    @param
    、
    @return
    、
    @returns
    、
    @throws
    、
    @exception
    、
    @see
    、
    @type
    )。应将参数名称、返回行为和异常信息融入正文描述中。

4. Technical Placement & Resolution

4. 技术放置与解析

  • Annotations (
    @override
    , etc.):
    Doc comments must be placed before metadata annotations.
  • Inherited Documentation: Avoid duplicating doc comments on
    @override
    members if the behavior does not differ from the superclass or interface. Dartdoc automatically inherits the base documentation.
  • 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
    .new
    syntax (e.g.,
    [ClassName.new]
    ).
  • 注解(
    @override
    等)
    :文档注释必须放在元数据注解之前。
  • 继承文档:如果
    @override
    成员的行为与父类或接口无差异,避免重复编写文档注释。Dartdoc会自动继承基础文档。
  • Getter/Setter对:如果属性同时有getter和setter,仅在getter上放置文档注释。如果两者都添加文档,工具会发出警告。
  • 默认构造函数:要在文档注释中链接到默认的无命名构造函数,必须使用
    .new
    语法(例如
    [ClassName.new]
    )。

5. Linking and Markdown

5. 链接与Markdown格式

  • Square brackets (
    [identifier]
    ) 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.
  • No parentheses in method links: Avoid parentheses in links (e.g., use
    [String.contains]
    , not
    [String.contains()]
    ).
  • Backticks for keywords & literals: Use backticks for keywords, literals, and arbitrary expressions (e.g.
    `null`
    ,
    `true`
    ,
    `void`
    ). Never put keywords in square brackets (avoid
    [null]
    or
    [true]
    ).
  • Out-of-Scope Links: If you need to link to a symbol that is not imported by the current library, use the
    @docImport
    directive at the top of the file (on the
    library;
    declaration) rather than adding a standard
    import
    .
  • Code Blocks: For code samples, always label the language fence. Use
    ```dart
    for Dart, or
    ```sh
    for shell commands. Do not leave code blocks unlabelled, as Dartdoc will attempt to auto-detect the language and frequently guesses wrong.
  • 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.
  • 作用域内符号用方括号(
    [identifier]
    )
    :使用方括号链接到任意作用域内的标识符(参数、类、方法、字段和顶层函数),以便dartdoc解析它们。切勿对参数使用反引号。
  • 方法链接中不要加括号:链接中避免使用括号(例如使用
    [String.contains]
    ,而非
    [String.contains()]
    )。
  • 关键字与字面量用反引号:关键字、字面量和任意表达式使用反引号包裹(例如
    `null`
    、
    `true`
    、
    `void`
    )。切勿将关键字放在方括号中(避免
    [null]
    或
    [true]
    )。
  • 跨作用域链接:如果需要链接到当前库未导入的符号,请在文件顶部的
    library;
    声明上使用
    @docImport
    指令,而非添加标准的
    import
    语句。
  • 代码块:代码示例必须标注语言围栏。Dart代码使用
    ```dart
    ,shell命令使用
    ```sh
    。不要让代码块无标注,否则Dartdoc会尝试自动检测语言,且经常判断错误。
  • 格式规范:首段之后使用标准Markdown格式(加粗、列表等),充分说明边缘情况、抛出的异常以及调用者无法看到的内部行为。

6. Verification

6. 验证

After writing or updating doc comments:
  1. Run
    dart analyze
    to ensure all bracketed references resolve properly without triggering
    comment_references
    warnings.
  2. (Optional) Run
    dart doc
    to verify the generated documentation renders cleanly.
编写或更新文档注释后:
  1. 运行
    dart analyze
    确保所有方括号引用都能正确解析,不会触发
    comment_references
    警告。
  2. (可选)运行
    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].