学习Flutter开发要了解的Dart 编码规范

2019-08-0607:23:32APP与小程序开发Comments2,878 views字数 7862阅读模式

编码习惯都是因人而异的,并没有所谓的最佳方案。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

如果你是一个人开发,当然不需要在意这些问题,但是如果你的代码需要展现给别人,或者你需要与别人协同开发,编码规范就非常有必要了。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

下面,将会从官方文档中选取最基本,最典型,发生率较高的一些情况,作为规范说明。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

✅表示正面做法,❌表示反面做法文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

样式规范

命名

DO: 类, 枚举, 类型定义, 以及泛型,都需要使用大写开头的驼峰命名法文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

✅
class SliderMenu { ... }

class HttpRequest { ... }

typedef Predicate<T> = bool Function(T value);
复制代码

在使用注解时候,也应该这样文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

✅

class Foo {
  const Foo([arg]);
}

@Foo(anArg)
class A { ... }

@Foo()
class B { ... }
复制代码

不过为一个类的构造函数添加注解时,你可能需要创建一个小写开头的注解变量文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

✅

const foo = Foo();

@foo
class C { ... }
复制代码

DO: 命名库、包、目录、dart文件都应该是小写加上下划线文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

✅

library peg_parser.source_scanner;

import 'file_system.dart';
import 'slider_menu.dart';
复制代码
❌

library pegparser.SourceScanner;

import 'file-system.dart';
import 'SliderMenu.dart';
复制代码

DO: 将引用使用as转换的名字也应该是小写下划线文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

✅

import 'dart:math' as math;
import 'package:angular_components/angular_components'
    as angular_components;
import 'package:js/js.dart' as js;
复制代码
❌

import 'dart:math' as Math;
import 'package:angular_components/angular_components'
    as angularComponents;
import 'package:js/js.dart' as JS;
复制代码

DO: 变量名、方法、参数名都应该是小写开头的驼峰命名法文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

✅

var item;

HttpRequest httpRequest;

void align(bool clearItems) {
  // ...
}
复制代码
✅

const pi = 3.14;
const defaultTimeout = 1000;
final urlScheme = RegExp('^([a-z]+):');

class Dice {
  static final numberGenerator = Random();
}
复制代码
❌

const PI = 3.14;
const DefaultTimeout = 1000;
final URL_SCHEME = RegExp('^([a-z]+):');

class Dice {
  static final NUMBER_GENERATOR = Random();
}

复制代码

花括号

DO: 只有一个if语句且没有else的时候,并且在一行内能够很好的展示,就可以不用花括号文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

if (arg == null) return defaultValue;
复制代码

但是如果一行内展示比较勉强的话,就需要用花括号了:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

if (overflowChars != other.overflowChars) {
  return overflowChars < other.overflowChars;
}
复制代码
if (overflowChars != other.overflowChars)
  return overflowChars < other.overflowChars;
复制代码

文档规范

DO: 在dart的注释中,更加推荐使用///而非//文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

✅

/// The number of characters in this chunk when unsplit.
int get length => ...
复制代码
❌

// The number of characters in this chunk when unsplit.
int get length => ...
复制代码

至于为什么要这样做,官方表示是由于历史原因以及他们觉得这个在某些情况下看起来更方便阅读。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

DO: 文档注释应该以一句简明的话开头文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

✅

/// Deletes the file at [path] from the file system.
void delete(String path) {
  ...
}
复制代码
❌

/// Depending on the state of the file system and the user's permissions,
/// certain operations may or may not be possible. If there is no file at
/// [path] or it can't be accessed, this function throws either [IOError]
/// or [PermissionError], respectively. Otherwise, this deletes the file.
void delete(String path) {
  ...
}
复制代码

DO: 将注释的第一句与其他内容分隔开来文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

✅

/// 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) {
  ...
}
复制代码
❌

/// 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) {
  ...
}
复制代码

DO: 使用方括号去声明参数、返回值以及抛出的异常文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

❌

/// Defines a flag with the given name and abbreviation.
///
/// @param name The name of the flag.
/// @param abbr The abbreviation for the flag.
/// @returns The new flag.
/// @throws ArgumentError If there is already an option with
///     the given name or abbreviation.
Flag addFlag(String name, String abbr) => ...
复制代码
✅

/// Defines a flag.
///
/// Throws an [ArgumentError] if there is already an option named [name] or
/// there is already an option using abbreviation [abbr]. Returns the new flag.
Flag addFlag(String name, String abbr) => ...
复制代码

使用规范

依赖

PREFER: 推荐使用相对路径导入依赖文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

如果项目结构如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

my_package
└─ lib
   ├─ src
   │  └─ utils.dart
   └─ api.dart
复制代码

想要在 api.dart 中导入 utils.dart文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

✅

import 'src/utils.dart';
复制代码
❌

import 'package:my_package/src/utils.dart';
复制代码

赋值

DO: 使用??将null值做一个转换文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

在dart中 ?? 操作符表示当一个值为空时会给它赋值 ?? 后面的数据文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

if (optionalThing?.isEnabled) {
  print("Have enabled thing.");
}
复制代码

optionalThing 为空的时候,上面就会有空指针异常了。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

这里说明一下。 ?. 操作符相当于做了一次判空操作,只有当 optionalThing 不为空的时候才会调用 isEnabled 参数,当 optionalThing 为空的话默认返回null,用在if判断句中自然就不行了文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

下面是正确做法文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

✅

// 如果为空的时候你想返回false的话:
optionalThing?.isEnabled ?? false;

// 如果为空的时候你想返回ture的话:
optionalThing?.isEnabled ?? true;
复制代码
❌

optionalThing?.isEnabled == true;

optionalThing?.isEnabled == false;
复制代码

字符串

在dart中,不推荐使用 + 去连接两个字符串文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

DO: 使用回车键直接分隔字符串文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

✅

raiseAlarm(
    'ERROR: Parts of the spaceship are on fire. Other '
    'parts are overrun by martians. Unclear which are which.');
复制代码
❌

raiseAlarm('ERROR: Parts of the spaceship are on fire. Other ' +
    'parts are overrun by martians. Unclear which are which.');
复制代码

PREFER: 使用${}来连接字符串与变量值文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

'Hello, $name! You are ${year - birth} years old.';
复制代码
'Hello, ' + name + '! You are ' + (year - birth).toString() + ' y...';
复制代码

集合

dart中创建空的可扩展 List 有两种方法: []List();创建空的 HashMap 有三种方法: {}, Map(),和 LinkedHashMap()文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

如果要创建不可扩展的列表或其他一些自定义集合类型,那么务必使用构造函数。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

DO: 尽可能使用简单的字面量创建集合文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

✅

var points = [];
var addresses = {};
复制代码
❌

var points = List();
var addresses = Map();
复制代码

当你想要指定类型的时候文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

✅

var points = <Point>[];
var addresses = <String, Address>{};
复制代码
❌

var points = List<Point>();
var addresses = Map<String, Address>();
复制代码

DON’T: 不要使用.lenght的方法去表示一个集合是空的文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

if (lunchBox.isEmpty) return 'so hungry...';
if (words.isNotEmpty) return words.join(' ');
复制代码
if (lunchBox.length == 0) return 'so hungry...';
if (!words.isEmpty) return words.join(' ');
复制代码

CONSIDER: 考虑使用高阶方法转换序列文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

var aquaticNames = animals
    .where((animal) => animal.isAquatic)
    .map((animal) => animal.name);
复制代码

AVOID: 避免使用带有函数字面量的Iterable.forEach()文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

forEach()函数在JavaScript中被广泛使用,因为内置的for-in循环不能达到你通常想要的效果。在Dart中,如果要迭代序列,那么惯用的方法就是使用循环。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

for (var person in people) {
  ...
}
复制代码
❌

people.forEach((person) {
  ...
});
复制代码

DON’T: 不要使用 List.from() 除非你打算更改结果的类型文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

有两种方法去获取 Iterable,分别是List.from()和Iterable.toList()文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

✅

// 创建一个List<int>:
var iterable = [1, 2, 3];

// 输出"List<int>":
print(iterable.toList().runtimeType);
复制代码
❌

// 创建一个List<int>:
var iterable = [1, 2, 3];

// 输出"List<dynamic>":
print(List.from(iterable).runtimeType);
复制代码

DO: 使用 whereType()去用类型过滤一个集合文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

❌

var objects = [1, "a", 2, "b", 3];
var ints = objects.where((e) => e is int);
复制代码
❌

var objects = [1, "a", 2, "b", 3];
var ints = objects.where((e) => e is int).cast<int>();

复制代码
✅

var objects = [1, "a", 2, "b", 3];
var ints = objects.whereType<int>();
复制代码

参数

DO: 使用 = 给参数设置默认值文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

✅

void insert(Object item, {int at = 0}) { ... }
复制代码
❌

void insert(Object item, {int at: 0}) { ... }
复制代码

DON’T: 不要将参数的默认值设置为 null文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

✅

void error([String message]) {
  stderr.write(message ?? '\n');
}
复制代码
❌

void error([String message = null]) {
  stderr.write(message ?? '\n');
}
复制代码

变量

AVOID: 避免存储可以计算的值文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

❌

class Circle {
  num _radius;
  num get radius => _radius;
  set radius(num value) {
    _radius = value;
    _recalculate();
  }

  num _area;
  num get area => _area;

  num _circumference;
  num get circumference => _circumference;

  Circle(this._radius) {
    _recalculate();
  }

  void _recalculate() {
    _area = pi * _radius * _radius;
    _circumference = pi * 2.0 * _radius;
  }
}
复制代码
✅

class Circle {
  num radius;

  Circle(this.radius);

  num get area => pi * radius * radius;
  num get circumference => pi * 2.0 * radius;
}
复制代码

成员

DON’T: 不要写没必要的getter 和 setter文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

✅

class Box {
  var contents;
}
复制代码
❌

class Box {
  var _contents;
  get contents => _contents;
  set contents(value) {
    _contents = value;
  }
}
复制代码

构造函数

DO: 尽可能使用简单的初始化形式文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

❌

class Point {
  num x, y;
  Point(num x, num y) {
    this.x = x;
    this.y = y;
  }
}
复制代码
✅

class Point {
  num x, y;
  Point(this.x, this.y);
}
复制代码

DON’T: 不要使用 new 来创建对象文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

dart中不需要new文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

✅

Widget build(BuildContext context) {
  return Row(
    children: [
      RaisedButton(
        child: Text('Increment'),
      ),
      Text('Click!'),
    ],
  );
}
复制代码
❌

Widget build(BuildContext context) {
  return new Row(
    children: [
      new RaisedButton(
        child: new Text('Increment'),
      ),
      new Text('Click!'),
    ],
  );
}
复制代码

DON’T: 不要使用多余的 const 修饰对象文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

✅

const primaryColors = [
  Color("red", [255, 0, 0]),
  Color("green", [0, 255, 0]),
  Color("blue", [0, 0, 255]),
];
复制代码
❌

const primaryColors = const [
  const Color("red", const [255, 0, 0]),
  const Color("green", const [0, 255, 0]),
  const Color("blue", const [0, 0, 255]),
];
复制代码

异常处理

DO: 使用 rethrow 重新抛出异常文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

❌

try {
  somethingRisky();
} catch (e) {
  if (!canHandle(e)) throw e;
  handle(e);
}
复制代码
✅

try {
  somethingRisky();
} catch (e) {
  if (!canHandle(e)) rethrow;
  handle(e);
}
复制代码

设计规范

AVOID: 避免为了实现流式调用而让方法返回this文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

✅

var buffer = StringBuffer()
  ..write('one')
  ..write('two')
  ..write('three');
复制代码
❌

var buffer = StringBuffer()
    .write('one')
    .write('two')
    .write('three');
复制代码

AVOID: 避免使用 FutureOr<T> 作为返回类型文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

✅

Future<int> triple(FutureOr<int> value) async => (await value) * 3;
复制代码
❌

FutureOr<int> triple(FutureOr<int> value) {
  if (value is int) return value * 3;
  return (value as Future<int>).then((v) => v * 3);
}
复制代码

AVOID: 避免将bool值直接作为输入参数文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

❌

new Task(true);
new Task(false);
new ListBox(false, true, true);
new Button(false);
复制代码
✅

Task.oneShot();
Task.repeating();
ListBox(scroll: true, showScrollbars: true);
Button(ButtonState.enabled);
复制代码

DON’T: 不要在自定义的 == operator 方法中进行判空文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

✅

class Person {
  final String name;
  // ···
  bool operator ==(other) => other is Person && name == other.name;

  int get hashCode => name.hashCode;
}
复制代码
❌

class Person {
  final String name;
  // ···
  bool operator ==(other) => other != null && ...
}

作者:安卓小哥
链接:https://juejin.im/post/5d43a0efe51d4561af16dca1
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html

文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/15073.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/xcx/15073.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定