dart effective-用法

 

1.库

 在 part of 后要使用相对路径的字符串,不要直接使用库名称

part "some/other/file.dart";//好
part of my_library;//坏

 导入自己的lib库时要使用相对路径 

import 'src/utils.dart'; //好
import 'package:my_package/src/utils.dart';//坏

2.bool

当值为null并且结果不能接受null时,应转成bool值

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

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

3.String

 一个长字符串换行时不要用+做连接符,加号应该被省略

  String a = 'ERROR: Parts of the spaceship are on fire. Other '
      'parts are overrun by martians. Unclear which are which.';

字符串插值要使用$,不要使用加号

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

字符串插值是单个变量时,尽量省略使用花括号

'Hi, $name!'
    "Wear your wildest $decade's outfit." 
    'Wear your wildest ${decade}s outfit.' //

'Hi, ${name}!'
    "Wear your wildest ${decade}'s outfit."//

4.集合

 dart的三个核心集合,初始化未命名的构造函数时

var points = <Point>[];
var addresses = <String, Address>{};
var counts = <int>{};

 坏

var points = List<Point>();
var addresses = Map<String, Address>();
var counts = Set<int>();

 

判断集合中是否有数据时,不要使用.lenth,应该使用.empty

main(List<String> args) {
  var points = <int>[];
  if (points.isEmpty) {} //
  if (points.length == 0) {} //
}

 如果要根据一个集合生成新集合时,考虑使用高阶函数代替for循环

var points = <int>[1, 2, 3, 4, 5];
  
var items = points.where((element) => element > 3);//

  var temp = [];   //
  for (var item in points) {
    if (item > 3) temp.add(item);
  }

.forEach让不让用没看懂!!! 

points.forEach((element) => {print(element)});

迭代结果如果不转化类型使用.toList()、如果换类型使用List.from()

var copy1 = iterable.toList();
var copy2 = List.from(iterable);

如果想要在混合类型的集合中过滤出指定类型,使用 .whereType

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

 使用.from !!没看懂

var stuff = <dynamic>[1, 2];
var ints = List<int>.from(stuff); //
var ints = stuff.toList().cast<int>();//

 

5.函数

 

6.参数

带默认值的参数使用赋值使用 = ,不要使用:

void insert(Object item, {int at = 0}) { ... } //
void insert(Object item, {int at: 0}) { ... } //

不要明确把参数赋值为null

void error([String message]) {} //
void error([String message = null]) {}//

7.变量

 不要把变量显示赋值null

int _nextId; //
int _nextId=null; //

8.成员

不要包装不必要的get和set属性

 

优先使用final字段来创建只读属性

class Box {
  final contents = [];
}

class Box {
  var _contents;
  get contents => _contents;
}

用于属性的=>

=>不仅用于函数表达式,还可以用于返回属性

num get x => center.x;
set x(num value) => center = Point(value, center.y);

this

 尽可能在声明时初始化字段

class Folder {
  final String name;
  final List<Document> contents = [];

  Folder(this.name);
  Folder.temp() : name = 'temporary';
}

 

9.构造函数

直接从构造函数初始化

//
class Point {
  double x, y;
  Point(this.x, this.y);
}
//
class Point {
  double x, y;
  Point(double x, double y) {
    this.x = x;
    this.y = y;
  }
}

 空构造函数使用; 不要使用{}

class Point {
  double x, y;

  Point(this.x, this.y);//
  Point(this.x, this.y){}//
}

不要使用new关键字

从dart2开始new变成可选关键字

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

 

10.错误处理

 

11.异步

优先使用asyncawait

 

async没有任何用处时,请勿使用

Future<void> afterTwoThings(Future<void> first, Future<void> second) {
  return Future.wait([first, second]);
}

使用async的情况

  • 您正在使用await

  • 您正在异步返回错误。async然后throw比短return Future.error(...)

  • 您正在返回一个值,并且希望将来将其隐式包装。 async比短Future.value(...)

Future<void> usesAwait(Future<String> later) async {
  print(await later);
}

Future<void> asyncError() async {
  throw 'Error!';
}

Future<void> asyncValue() async => 'value';

 

posted @ 2020-09-18 09:09  富坚老贼  阅读(165)  评论(0编辑  收藏  举报