无论对于哪门语言,写注释都是很难的,但是难也得写。可能你在设计程序的时候灵光一闪,想到了一个绝佳的思路,但是过了半年一年之后,可能这个思路就想不起来了,代码也看不懂了,更不要说别人能看懂你的代码了。
- 不需要出现在文档中的注释都应该使用
//
。 - 需要生成文档的注释 要 使用
///
文档注释来注释成员和类型。 - 要在文档注释开头有一个单句总结 要 让文档注释的第一句从段落中分开。
/// Deletes the file at [path]. /// /// Throws an [IOError] if the file could not be found. Throws a /// [PermissionError] if the file is present but could not be deleted. void delete(String path) { ... } 复制代码
- 如果一个属性同时包含 getter 和 setter,请只为其中一个添加文档。
dart doc
命令会将 getter 和 setter 作为同一个属性进行处理,而如果它们都包含文档注释,dart docs
命令会将 setter 的文档忽略。
/// The pH level of the water in the pool. /// /// Ranges from 0-14, representing acidic to basic, with 7 being neutral. int get phLevel => ... set phLevel(int level) => ... 复制代码
- 推荐使用名词短语来开始库和类型注释。
/// A chunk of non-breaking output text terminated by a hard or soft newline. /// /// ... class Chunk { ... } 复制代码
- 考虑 在文档注释中添加示例代码。
/// Returns the lesser of two numbers. /// /// ```dart /// min(5, 3) == 3 /// ``` num min(num a, num b) => ... 复制代码
- 给变量,方法,或类型等名称加上方括号,则 dartdoc 会查找名称并链接到相关的 API 文档。括号是可选的,但是当你在引用一个方法或者构造函数时,可以让注释更清晰。可以链接到类的命名构造函数,或 变量,方法,类型等。
/// Throws a [StateError] if ... /// Similar to [Duration.inDays], but handles fractional days. /// To create a point, call [Point.new] or use [Point.polar] to .. 复制代码
- 要 把注释文档放到注解之前。
/// A button that can be flipped on and off. @Component(selector: 'toggle') class ToggleComponent {} 复制代码
不要把 @Component 放到第一行,要放到注释之后。
- 可以用 markdown 来格式代码,但不要滥用。
/// /// This sentence has *two* _emphasized_ words (italics) and **two** /// __strong__ ones (bold). /// /// A blank line creates a separate paragraph. It has some `inline code` /// delimited using backticks. /// /// * Unordered lists. /// * Look like ASCII bullet lists. /// * You can also use `-` or `+`. /// /// 1. Numbered lists. /// 2. Are, well, numbered. /// 1. But the values don't matter. /// /// * You can nest lists too. /// * They must be indented at least 4 spaces. /// * (Well, 5 including the space after `///`.) /// /// Code blocks are fenced in triple backticks: /// /// ```dart /// this.code /// .will /// .retain(its, formatting); /// ``` /// /// The code language (for syntax highlighting) defaults to Dart. You can /// specify it by putting the name of the language after the opening backticks: /// /// ```html /// <h1>HTML is magical!</h1> /// ``` /// /// Links can be: /// /// * https://www.just-a-bare-url.com /// * [with the URL inline](https://google.com) /// * [or separated out][ref link] /// /// [ref link]: https://google.com /// /// # A Header /// /// ## A subheader /// /// ### A subsubheader /// /// #### If you need this many levels of headers, you're doing it wrong 复制代码
- 可以用反引号来标代码
/// You can use [CodeBlockExample] like this: /// /// ```dart /// var example = CodeBlockExample(); /// print(example.isItGreat); // "Yes." /// ``` 复制代码
总之写注释的时候要简洁,清晰,切中要害。