多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] 下面的最佳实践适用于为类声明构造函数。 ## 尽可能使用初始化的形式。 许多字段直接从构造函数参数初始化,如: 以下是不推荐的写法: ~~~ 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); } ~~~ 构造函数参数前的this.语法称为“初始化形式”。你不能总是利用它。特别是,使用它意味着参数在初始化列表中不可见。但是,当你需要这样做时,你应该这样做。 ## 不要键入注释初始化的形式。 如果构造函数参数使用this.初始化一个字段,那么该参数的类型被理解为与字段的类型相同。 以下是推荐的写法: ~~~ class Point { int x, y; Point(this.x, this.y); } ~~~ 不要使用以下写法: ~~~ class Point { int x, y; Point(int this.x, int this.y); } ~~~ ## 对于空的构造函数体使用;而不是{}。 在Dart中,带有空主体的构造函数只能以分号结束。(事实上,const构造函数需要它。) 以下是推荐的写法: ~~~ class Point { int x, y; Point(this.x, this.y); } ~~~ 以下是不推荐的写法: ~~~ class Point { int x, y; Point(this.x, this.y) {} } ~~~ ## 不要使用new Dart2使new 关键字可选。即使在Dart 1中,它的含义也一直不清楚,因为工厂构造函数意味着新的调用可能仍然不会返回新的对象。 为了减少迁移的痛苦,这种语言仍然允许使用new,但是要考虑到它已被弃用,并将其从代码中删除。 以下是推荐的写法: ~~~ 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!'), ], ); } ~~~ ## 不要过多的使用const。 在表达式必须为常量的上下文中,const关键字是隐式的,不需要编写,也不应该编写。这些上下文是内部的任何表达式: * 一个const字面量集合。 * 一个const构造函数调用 * 一个元数据注释。 * const变量声明的初始化器。 * 在switch-case表达式中——在case的冒号(:)之前,而不是case的主体。 (默认值不包括在这个列表中,因为Dart的未来版本可能会支持非常量默认值。) Basically, any place where it would be an error to write new instead of const, Dart 2 allows you to omit the const. 基本上,任何使用new而不是const的地方都有可能出现错误,Dart 2允许你省略const。 >**译者注**:以上这句的翻译有点儿拗口。其实通俗的解释是这样的:比如颜色的rgb值[255, 0, 0]这其实是new初始化了一个数组(list集合),但是如果在之前加了const [255, 0, 0]就不对了 以下是正确写法: ~~~ 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]), ]; ~~~