[关闭]
@Rookie 2022-06-22T07:08:15.000000Z 字数 7660 阅读 1644

Flutter及Dart 编码规范

flutter


Flutter及Dart 编码规范

每个部分都有许多的例子说明,每个例子都会以下面五个词中的某些作为开头:

DO :表示你需要遵守的做法
DONT :表示这样的做法是非常不好的
PREFER :在多数情况下,都推荐的做法
AVOID : 在多数情况下,都应该避免的做法
CONSIDER : 需要你自己去斟酌的做法

在我看来,编码习惯都是因人而异的,并没有所谓的最佳方案。

如果你是一个人开发,当然不需要在意这些问题,但是如果你的代码需要展现给别人,或者你需要与别人协同开发,编码规范就非常有必要了。

下面,将会从官方文档中选取最基本,最典型,发生率较高的一些情况,作为规范说明。

✅表示正面做法,❌表示反面做法

样式规范

命名
DO: 类, 枚举, 类型定义, 以及泛型,都需要使用大写开头的驼峰命名法

  1. ✅
  2. class SliderMenu { ... }
  3. class HttpRequest { ... }
  4. typedef Predicate<T> = bool Function(T value);

在使用注解时候,也应该这样

  1. ✅
  2. class Foo {
  3. const Foo([arg]);
  4. }
  5. @Foo(anArg)
  6. class A { ... }
  7. @Foo()
  8. class B { ... }

不过为一个类的构造函数添加注解时,你可能需要创建一个小写开头的注解变量

  1. ✅
  2. const foo = Foo();
  3. @foo
  4. class C { ... }

DO: 命名库、包、目录、dart文件都应该是小写加上下划线

  1. ✅
  2. library peg_parser.source_scanner;
  3. import 'file_system.dart';
  4. import 'slider_menu.dart';
  1. ❌
  2. library pegparser.SourceScanner;
  3. import 'file-system.dart';
  4. import 'SliderMenu.dart';

DO: 将引用使用as转换的名字也应该是小写下划线

  1. ✅
  2. import 'dart:math' as math;
  3. import 'package:angular_components/angular_components'
  4. as angular_components;
  5. import 'package:js/js.dart' as js;
  1. ❌
  2. import 'dart:math' as Math;
  3. import 'package:angular_components/angular_components'
  4. as angularComponents;
  5. import 'package:js/js.dart' as JS;

DO: 变量名、方法、参数名都应该是小写开头的驼峰命名法

  1. ✅
  2. var item;
  3. HttpRequest httpRequest;
  4. void align(bool clearItems) {
  5. // ...
  6. }
  1. ✅
  2. const pi = 3.14;
  3. const defaultTimeout = 1000;
  4. final urlScheme = RegExp('^([a-z]+):');
  5. class Dice {
  6. static final numberGenerator = Random();
  7. }
  1. ❌
  2. const PI = 3.14;
  3. const DefaultTimeout = 1000;
  4. final URL_SCHEME = RegExp('^([a-z]+):');
  5. class Dice {
  6. static final NUMBER_GENERATOR = Random();
  7. }

花括号

DO: 只有一个if语句且没有else的时候,并且在一行内能够很好的展示,就可以不用花括号

  1. ✅
  2. if (arg == null) return defaultValue;

但是如果一行内展示比较勉强的话,就需要用花括号了:

  1. ✅
  2. if (overflowChars != other.overflowChars) {
  3. return overflowChars < other.overflowChars;
  4. }
  1. ❌
  2. if (overflowChars != other.overflowChars)
  3. return overflowChars < other.overflowChars;

文档规范

DO: 在dart的注释中,更加推荐使用///而非//

  1. ✅
  2. /// The number of characters in this chunk when unsplit.
  3. int get length => ...
  1. ❌
  2. // The number of characters in this chunk when unsplit.
  3. int get length => ...

至于为什么要这样做,官方表示是由于历史原因以及他们觉得这个在某些情况下看起来更方便阅读。

DO: 文档注释应该以一句简明的话开头

  1. ✅
  2. /// Deletes the file at [path] from the file system.
  3. void delete(String path) {
  4. ...
  5. }
  1. ❌
  2. /// Depending on the state of the file system and the user's permissions,
  3. /// certain operations may or may not be possible. If there is no file at
  4. /// [path] or it can't be accessed, this function throws either [IOError]
  5. /// or [PermissionError], respectively. Otherwise, this deletes the file.
  6. void delete(String path) {
  7. ...
  8. }
  9. DO: 将注释的第一句与其他内容分隔开来
  1. ✅
  2. /// Deletes the file at [path].
  3. ///
  4. /// Throws an [IOError] if the file could not be found. Throws a
  5. /// [PermissionError] if the file is present but could not be deleted.
  6. void delete(String path) {
  7. ...
  8. }
  1. ❌
  2. /// Deletes the file at [path]. Throws an [IOError] if the file could not
  3. /// be found. Throws a [PermissionError] if the file is present but could
  4. /// not be deleted.
  5. void delete(String path) {
  6. ...
  7. }

DO: 使用方括号去声明参数、返回值以及抛出的异常

  1. ❌
  2. /// Defines a flag with the given name and abbreviation.
  3. ///
  4. /// @param name The name of the flag.
  5. /// @param abbr The abbreviation for the flag.
  6. /// @returns The new flag.
  7. /// @throws ArgumentError If there is already an option with
  8. /// the given name or abbreviation.
  9. Flag addFlag(String name, String abbr) => ...
  1. ✅
  2. /// Defines a flag.
  3. ///
  4. /// Throws an [ArgumentError] if there is already an option named [name] or
  5. /// there is already an option using abbreviation [abbr]. Returns the new flag.
  6. Flag addFlag(String name, String abbr) => ...

使用规范

依赖

PREFER: 推荐使用相对路径导入依赖

如果项目结构如下:

  1. my_package
  2. └─ lib
  3. ├─ src
  4. │ └─ utils.dart
  5. └─ api.dart

想要在 api.dart 中导入 utils.dart

  1. ✅
  2. import 'src/utils.dart';
  1. ❌
  2. import 'package:my_package/src/utils.dart';

赋值

DO: 使用??将null值做一个转换

在dart中 ?? 操作符表示当一个值为空时会给它赋值 ?? 后面的数据

  1. ❌
  2. if (optionalThing?.isEnabled) {
  3. print("Have enabled thing.");
  4. }

当 optionalThing 为空的时候,上面就会有空指针异常了。

这里说明一下。 ?. 操作符相当于做了一次判空操作,只有当 optionalThing 不为空的时候才会调用 isEnabled 参数,当 optionalThing 为空的话默认返回null,用在if判断句中自然就不行了

下面是正确做法

  1. ✅
  2. // 如果为空的时候你想返回false的话:
  3. optionalThing?.isEnabled ?? false;
  4. // 如果为空的时候你想返回ture的话:
  5. optionalThing?.isEnabled ?? true;
  1. ❌
  2. optionalThing?.isEnabled == true;
  3. optionalThing?.isEnabled == false;

字符串

在dart中,不推荐使用 + 去连接两个字符串

DO: 使用回车键直接分隔字符串

  1. ✅
  2. raiseAlarm(
  3. 'ERROR: Parts of the spaceship are on fire. Other '
  4. 'parts are overrun by martians. Unclear which are which.');
  1. ❌
  2. raiseAlarm('ERROR: Parts of the spaceship are on fire. Other ' +
  3. 'parts are overrun by martians. Unclear which are which.');
  4. PREFER: 使用${}来连接字符串与变量值
  1. ✅
  2. 'Hello, $name! You are ${year - birth} years old.';
  1. ❌
  2. 'Hello, ' + name + '! You are ' + (year - birth).toString() + ' y...';

集合

dart中创建空的可扩展 List 有两种方法: [] 和 List();创建空的 HashMap 有三种方法: {}, Map(),和 LinkedHashMap()

如果要创建不可扩展的列表或其他一些自定义集合类型,那么务必使用构造函数。

DO: 尽可能使用简单的字面量创建集合

  1. ✅
  2. var points = [];
  3. var addresses = {};
  1. ❌
  2. var points = List();
  3. var addresses = Map();

当你想要指定类型的时候

  1. ✅
  2. var points = <Point>[];
  3. var addresses = <String, Address>{};
  1. ❌
  2. var points = List<Point>();
  3. var addresses = Map<String, Address>();

DON’T: 不要使用.lenght的方法去表示一个集合是空的

  1. ✅
  2. if (lunchBox.isEmpty) return 'so hungry...';
  3. if (words.isNotEmpty) return words.join(' ');
  1. ❌
  2. if (lunchBox.length == 0) return 'so hungry...';
  3. if (!words.isEmpty) return words.join(' ');
  4. CONSIDER: 考虑使用高阶方法转换序列
  5. var aquaticNames = animals
  6. .where((animal) => animal.isAquatic)
  7. .map((animal) => animal.name);

AVOID: 避免使用带有函数字面量的Iterable.forEach()

forEach()函数在JavaScript中被广泛使用,因为内置的for-in循环不能达到你通常想要的效果。在Dart中,如果要迭代序列,那么惯用的方法就是使用循环。

  1. ✅
  2. for (var person in people) {
  3. ...
  4. }
  1. ❌
  2. people.forEach((person) {
  3. ...
  4. });

DON’T: 不要使用 List.from() 除非你打算更改结果的类型

有两种方法去获取 Iterable,分别是List.from()和Iterable.toList()

  1. ✅
  2. // 创建一个List<int>:
  3. var iterable = [1, 2, 3];
  4. // 输出"List<int>":
  5. print(iterable.toList().runtimeType);
  1. ❌
  2. // 创建一个List<int>:
  3. var iterable = [1, 2, 3];
  4. // 输出"List<dynamic>":
  5. print(List.from(iterable).runtimeType);

DO: 使用 whereType()去用类型过滤一个集合

  1. ❌
  2. var objects = [1, "a", 2, "b", 3];
  3. var ints = objects.where((e) => e is int);
  1. ❌
  2. var objects = [1, "a", 2, "b", 3];
  3. var ints = objects.where((e) => e is int).cast<int>();
  1. ✅
  2. var objects = [1, "a", 2, "b", 3];
  3. var ints = objects.whereType<int>();
  4. 参数
  5. DO: 使用 = 给参数设置默认值
  1. ✅
  2. void insert(Object item, {int at = 0}) { ... }
  1. ❌
  2. void insert(Object item, {int at: 0}) { ... }

DON’T: 不要将参数的默认值设置为 null

  1. ✅
  2. void error([String message]) {
  3. stderr.write(message ?? '\n');
  4. }
  1. ❌
  2. void error([String message = null]) {
  3. stderr.write(message ?? '\n');
  4. }

变量

AVOID: 避免存储可以计算的值

  1. ❌
  2. class Circle {
  3. num _radius;
  4. num get radius => _radius;
  5. set radius(num value) {
  6. _radius = value;
  7. _recalculate();
  8. }
  9. num _area;
  10. num get area => _area;
  11. num _circumference;
  12. num get circumference => _circumference;
  13. Circle(this._radius) {
  14. _recalculate();
  15. }
  16. void _recalculate() {
  17. _area = pi * _radius * _radius;
  18. _circumference = pi * 2.0 * _radius;
  19. }
  20. }
  1. ✅
  2. class Circle {
  3. num radius;
  4. Circle(this.radius);
  5. num get area => pi * radius * radius;
  6. num get circumference => pi * 2.0 * radius;
  7. }

成员

DON’T: 不要写没必要的getter 和 setter

  1. ✅
  2. class Box {
  3. var contents;
  4. }
  1. ❌
  2. class Box {
  3. var _contents;
  4. get contents => _contents;
  5. set contents(value) {
  6. _contents = value;
  7. }
  8. }

构造函数

DO: 尽可能使用简单的初始化形式

  1. ❌
  2. class Point {
  3. num x, y;
  4. Point(num x, num y) {
  5. this.x = x;
  6. this.y = y;
  7. }
  8. }
  1. ✅
  2. class Point {
  3. num x, y;
  4. Point(this.x, this.y);
  5. }

DON’T: 不要使用 new 来创建对象

dart中不需要new

  1. ✅
  2. Widget build(BuildContext context) {
  3. return Row(
  4. children: [
  5. RaisedButton(
  6. child: Text('Increment'),
  7. ),
  8. Text('Click!'),
  9. ],
  10. );
  11. }
  1. ❌
  2. Widget build(BuildContext context) {
  3. return new Row(
  4. children: [
  5. new RaisedButton(
  6. child: new Text('Increment'),
  7. ),
  8. new Text('Click!'),
  9. ],
  10. );
  11. }

DON’T: 不要使用多余的 const 修饰对象

  1. ✅
  2. const primaryColors = [
  3. Color("red", [255, 0, 0]),
  4. Color("green", [0, 255, 0]),
  5. Color("blue", [0, 0, 255]),
  6. ];
  1. ❌
  2. const primaryColors = const [
  3. const Color("red", const [255, 0, 0]),
  4. const Color("green", const [0, 255, 0]),
  5. const Color("blue", const [0, 0, 255]),
  6. ];

异常处理

DO: 使用 rethrow 重新抛出异常

  1. ❌
  2. try {
  3. somethingRisky();
  4. } catch (e) {
  5. if (!canHandle(e)) throw e;
  6. handle(e);
  7. }
  1. ✅
  2. try {
  3. somethingRisky();
  4. } catch (e) {
  5. if (!canHandle(e)) rethrow;
  6. handle(e);
  7. }

设计

AVOID: 避免为了实现流式调用而让方法返回this

  1. ✅
  2. var buffer = StringBuffer()
  3. ..write('one')
  4. ..write('two')
  5. ..write('three');
  1. ❌
  2. var buffer = StringBuffer()
  3. .write('one')
  4. .write('two')
  5. .write('three');

AVOID: 避免使用 FutureOr 作为返回类型

  1. ✅
  2. Future<int> triple(FutureOr<int> value) async => (await value) * 3;
  1. ❌
  2. FutureOr<int> triple(FutureOr<int> value) {
  3. if (value is int) return value * 3;
  4. return (value as Future<int>).then((v) => v * 3);
  5. }

AVOID: 避免将bool值直接作为输入参数

  1. ❌
  2. new Task(true);
  3. new Task(false);
  4. new ListBox(false, true, true);
  5. new Button(false);
  1. ✅
  2. Task.oneShot();
  3. Task.repeating();
  4. ListBox(scroll: true, showScrollbars: true);
  5. Button(ButtonState.enabled);
  6. DON’T: 不要在自定义的 == operator 方法中进行判空
  1. ✅
  2. class Person {
  3. final String name;
  4. // ···
  5. bool operator ==(other) => other is Person && name == other.name;
  6. int get hashCode => name.hashCode;
  7. }
  1. ❌
  2. class Person {
  3. final String name;
  4. // ···
  5. bool operator ==(other) => other != null && ...
  6. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注