Flutter入门实践

001.5 flutter之dart最佳实践

2020-04-04  本文已影响0人  码农二哥

Effective Dart: Usage

library my_library;
part "some/other/file.dart";

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

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

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

Booleans 布尔

// 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 字符串

// good(不推荐用在第一行字符串后写一个冗余的+加号)
raiseAlarm(
    'ERROR: Parts of the spaceship are on fire. Other '
    'parts are overrun by martians. Unclear which are which.');
// good
'Hello, $name! You are ${year - birth} years old.';
// 类似$name,name两边不要加冗余的小括号
'Hi, $name!'
    "Wear your wildest $decade's outfit."
    'Wear your wildest ${decade}s outfit.'

Collections

var points = [];// 不推荐 var points = List();
var addresses = {};// 不推荐 var addresses = Map();
var points = <Point>[];// 不推荐 var points = List<Point>();
var addresses = <String, Address>{};// 不推荐 var addresses = Map<String, Address>();
// 判断空不空,建议这样写,尽量避免.length,效率painfully slow
if (lunchBox.isEmpty) return 'so hungry...';
if (words.isNotEmpty) return words.join(' ');
// 推荐这种写法,避免for循环
var aquaticNames = animals
    .where((animal) => animal.isAquatic)
    .map((animal) => animal.name);
// js中经常用Iterable.forEach() ,但dart官网推荐用for
for (var person in people) {
  ...
}
// good
var iterable = [1, 2, 3];// Creates a List<int>:
print(iterable.toList().runtimeType);// Prints "List<int>":
var numbers = [1, 2.3, 4]; // List<num>.
numbers.removeAt(1); // Now it only contains integers.
var ints = List<int>.from(numbers);// change the type of the result

// ----------------------------------------
// bad
var iterable = [1, 2, 3];// Creates a List<int>:
print(List.from(iterable).runtimeType);// Prints "List<dynamic>":
// good
var objects = [1, "a", 2, "b", 3];
var ints = objects.whereType<int>();

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

Functions 函数相关

// good
void main() {
  localFunction() {
    ...
  }
}
// bad
void main() {
  var localFunction = () {
    ...
  };
}
// good
names.forEach(print);
// bad
names.forEach((name) {
  print(name);
});
void insert(Object item, {int at = 0}) { ... }//用等于号,不要用冒号,虽然也可以
// bad
void error([String message = null]) {//=null冗余,默认就是
  stderr.write(message ?? '\n');
}

Variables 变量

Members

Constructors 构造函数

// 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);
}
// good
class Point {
  int x, y;
  Point(this.x, this.y);
}

// bad
class Point {
  int x, y;
  Point(int this.x, int this.y);
}
// good (空实现就别写了,直接来个分号就行)
class Point {
  int x, y;
  Point(this.x, this.y);
}
// bad
class Point {
  int x, y;
  Point(this.x, this.y) {}
}
// bad, new关键字是可选的,进而是冗余的(dart2.0建议别写冗余代码了)
Widget build(BuildContext context) {
  return new Row(
    children: [
      new RaisedButton(
        child: new Text('Increment'),
      ),
      new Text('Click!'),
    ],
  );
}

Error handling

PREFER async/await over using raw futures.

// good 
Future<int> 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<int> 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;
  });
}

参考

上一篇下一篇

猜你喜欢

热点阅读