001.5 flutter之dart最佳实践

Effective Dart: Usage

  • DO use strings in part of directives.
    尽管part语法会导致一个库的源码被分散到多个文件中(一个库就一个文档多好哇),但dart官网还是推荐使用part的(这样主文件更能突显该库的核心功能,非核心功能放到别的文件嘛),因此对于下述两种写法,优选good:
library my_library;
part "some/other/file.dart";

// good
part of "../../my_library.dart";

// bad
part of my_library;
  • DON’T import libraries that are inside the src directory of another package.
    尽管可以,但尽量不要引用别人库的src中的代码

  • 在自己的库中引用自己的文件,dart官网推荐使用相对路径

my_package
└─ lib
   ├─ src
   │  └─ utils.dart
   └─ api.dart
// good
import 'src/utils.dart';

// bad
import 'package:my_package/src/utils.dart';

Booleans 布尔

  • DO use ?? to convert null to a boolean value.
    当一个表达式的结果有true, false, or null三种值,但只能使用true, false的时候(比如if语句的条件表达式不接受null,会抛异常的),强烈推荐使用??将null转为true或者false
// good
// If you want null to be false:
optionalThing?.isEnabled ?? false;

// If you want null to be true:
optionalThing?.isEnabled ?? true;

// easy like this
if (optionalThing?.isEnabled??true) {
  print("Have enabled thing.");
}

// ----------------------------------------
// bad
// If you want null to be false:
optionalThing?.isEnabled == true;//对于这种写法,别人很可能以为==true是冗余的,可以删除,但实际上是不可以的

// If you want null to be true:
optionalThing?.isEnabled != false;

Strings 字符串

  • DO use adjacent strings to concatenate string literals.
// good(不推荐用在第一行字符串后写一个冗余的+加号)
raiseAlarm(
    'ERROR: Parts of the spaceship are on fire. Other '
    'parts are overrun by martians. Unclear which are which.');
  • PREFER using interpolation to compose strings and values.(不要老想着用+加号去连接字符串)
// good
'Hello, $name! You are ${year - birth} years old.';
  • AVOID using curly braces in interpolation when not needed.
// 类似$name,name两边不要加冗余的小括号
'Hi, $name!'
    "Wear your wildest $decade's outfit."
    'Wear your wildest ${decade}s outfit.'

Collections

  • DO use collection literals when possible.
var points = [];// 不推荐 var points = List();
var addresses = {};// 不推荐 var addresses = Map();
var points = [];// 不推荐 var points = List();
var addresses = {};// 不推荐 var addresses = Map();
  • DON’T use .length to see if a collection is empty.
// 判断空不空,建议这样写,尽量避免.length,效率painfully slow
if (lunchBox.isEmpty) return 'so hungry...';
if (words.isNotEmpty) return words.join(' ');
  • CONSIDER using higher-order methods to transform a sequence.
// 推荐这种写法,避免for循环
var aquaticNames = animals
    .where((animal) => animal.isAquatic)
    .map((animal) => animal.name);
  • AVOID using Iterable.forEach() with a function literal.
// js中经常用Iterable.forEach() ,但dart官网推荐用for
for (var person in people) {
  ...
}
  • DON’T use List.from() unless you intend to change the type of the result.
// good
var iterable = [1, 2, 3];// Creates a List:
print(iterable.toList().runtimeType);// Prints "List":
var numbers = [1, 2.3, 4]; // List.
numbers.removeAt(1); // Now it only contains integers.
var ints = List.from(numbers);// change the type of the result

// ----------------------------------------
// bad
var iterable = [1, 2, 3];// Creates a List:
print(List.from(iterable).runtimeType);// Prints "List":
  • DO use whereType() to filter a collection by type.
// good
var objects = [1, "a", 2, "b", 3];
var ints = objects.whereType();

// ----------------------------------------
// bad
var objects = [1, "a", 2, "b", 3];
var ints = objects.where((e) => e is int);//it returns an Iterable, not Iterable
// bad
var objects = [1, "a", 2, "b", 3];
var ints = objects.where((e) => e is int).cast();//这样不麻烦吗?

  • DON’T use cast() when a nearby operation will do.
  • AVOID using cast().

Functions 函数相关

  • DO use a function declaration to bind a function to a name.
// good
void main() {
  localFunction() {
    ...
  }
}
// bad
void main() {
  var localFunction = () {
    ...
  };
}
  • DON’T create a lambda when a tear-off will do.
// good
names.forEach(print);
// bad
names.forEach((name) {
  print(name);
});
  • Parameters 函数参数
  • DO use = to separate a named parameter from its default value.
void insert(Object item, {int at = 0}) { ... }//用等于号,不要用冒号,虽然也可以
  • DON’T use an explicit default value of null.
// bad
void error([String message = null]) {//=null冗余,默认就是
  stderr.write(message ?? '\n');
}

Variables 变量

  • DON’T explicitly initialize variables to null.(默认就是)
  • AVOID storing what you can calculate.

Members

  • DON’T wrap a field in a getter and setter unnecessarily.
  • CONSIDER using => for simple members.
  • DON’T use this. except to redirect to a named constructor or to avoid shadowing.
  • DO initialize fields at their declaration when possible.

Constructors 构造函数

  • DO use initializing formals when possible.
// bad
class Point {
  num x, y;
  Point(num x, num y) {
    this.x = x;
    this.y = y;
  }
}
// good
class Point {
  num x, y;
  Point(this.x, this.y);
}
  • DON’T type annotate initializing formals.
// good
class Point {
  int x, y;
  Point(this.x, this.y);
}

// bad
class Point {
  int x, y;
  Point(int this.x, int this.y);
}
  • DO use ; instead of {} for empty constructor bodies.
// good (空实现就别写了,直接来个分号就行)
class Point {
  int x, y;
  Point(this.x, this.y);
}
// bad
class Point {
  int x, y;
  Point(this.x, this.y) {}
}
  • DON’T use new.
// bad, new关键字是可选的,进而是冗余的(dart2.0建议别写冗余代码了)
Widget build(BuildContext context) {
  return new Row(
    children: [
      new RaisedButton(
        child: new Text('Increment'),
      ),
      new Text('Click!'),
    ],
  );
}
  • DON’T use const redundantly.
    In contexts where an expression must be constant, the const keyword is implicit, doesn’t need to be written, and shouldn’t.

Error handling

PREFER async/await over using raw futures.

// good 
Future countActivePlayers(String teamName) async {
  try {
    var team = await downloadTeam(teamName);
    if (team == null) return 0;

    var players = await team.roster;
    return players.where((player) => player.isActive).length;
  } catch (e) {
    log.error(e);
    return 0;
  }
}
// bad
Future countActivePlayers(String teamName) {
  return downloadTeam(teamName).then((team) {
    if (team == null) return Future.value(0);

    return team.roster.then((players) {
      return players.where((player) => player.isActive).length;
    });
  }).catchError((e) {
    log.error(e);
    return 0;
  });
}
  • CONSIDER using higher-order methods to transform a stream.
  • AVOID using Completer directly.
  • DO test for Future when disambiguating a FutureOr whose type argument could be Object.

参考

  • https://dart.dev/guides/language/effective-dart/usage#dont-use-length-to-see-if-a-collection-is-empty

你可能感兴趣的:(001.5 flutter之dart最佳实践)