# Flutter Go代碼開發(fā)規(guī)范 0.1.0版
##代碼風(fēng)格
###標(biāo)識符三種類型
####大駝峰
類赴肚、枚舉、typedef和類型參數(shù)
```
class SliderMenu { ... }
class HttpRequest { ... }
typedef Predicate = bool Function(T value);
```
包括用于元數(shù)據(jù)注釋的類
```
class Foo {
const Foo([arg]);
}
@Foo(anArg)
class A { ... }
@Foo()
class B { ... }
```
####使用小寫加下劃線來命名庫和源文件
```
library peg_parser.source_scanner;
import 'file_system.dart';
import 'slider_menu.dart';
```
不推薦如下寫法:
```
library pegparser.SourceScanner;
import 'file-system.dart';
import 'SliderMenu.dart';
```
####使用小寫加下劃線來命名導(dǎo)入前綴
```
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;
```
####使用小駝峰法命名其他標(biāo)識符
```
var item;
HttpRequest httpRequest;
void align(bool clearItems) {
// ...
}
```
####優(yōu)先使用小駝峰法作為常量命名
```
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();
}
```
####不使用前綴字母
因為Dart可以告訴您聲明的類型碘耳、范圍撤卢、可變性和其他屬性,所以沒有理由將這些屬性編碼為標(biāo)識符名稱揍瑟。
```
defaultTimeout
```
不推薦如下寫法:
```
kDefaultTimeout
```
###排序
為了使你的文件前言保持整潔少欺,我們有規(guī)定的命令喳瓣,指示應(yīng)該出現(xiàn)在其中。每個“部分”應(yīng)該用空行分隔赞别。
####在其他引入之前引入所需的dart庫
```
import 'dart:async';
import 'dart:html';
import 'package:bar/bar.dart';
import 'package:foo/foo.dart';
```
####在相對引入之前先引入在包中的庫
```
import 'package:bar/bar.dart';
import 'package:foo/foo.dart';
import 'util.dart';
```
####第三方包的導(dǎo)入先于其他包
```
import 'package:bar/bar.dart';
import 'package:foo/foo.dart';
import 'package:my_package/util.dart';
```
####在所有導(dǎo)入之后畏陕,在單獨的部分中指定導(dǎo)出
```
import 'src/error.dart';
import 'src/foo_bar.dart';
export 'src/error.dart';
```
不推薦如下寫法:
```
import 'src/error.dart';
export 'src/error.dart';
import 'src/foo_bar.dart';
```
###所有流控制結(jié)構(gòu),請使用大括號
這樣做可以避免懸浮的else問題
```
if (isWeekDay) {
print('Bike to work!');
} else {
print('Go dancing or read a book!');
}
```
####例外
一個if語句沒有else子句氯庆,其中整個if語句和then主體都適合一行蹭秋。在這種情況下,如果你喜歡的話堤撵,你可以去掉大括號
```
if (arg == null) return defaultValue;
```
如果流程體超出了一行需要分劃請使用大括號:
```
if (overflowChars != other.overflowChars) {
return overflowChars < other.overflowChars;
}
```
不推薦如下寫法:
```
if (overflowChars != other.overflowChars)
return overflowChars < other.overflowChars;
```
##注釋
###要像句子一樣格式化
除非是區(qū)分大小寫的標(biāo)識符仁讨,否則第一個單詞要大寫。以句號結(jié)尾(或“!”或“?”)实昨。對于所有的注釋都是如此:doc注釋洞豁、內(nèi)聯(lián)內(nèi)容,甚至TODOs荒给。即使是一個句子片段丈挟。
```
greet(name) {
// Assume we have a valid name.
print('Hi, $name!');
}
```
不推薦如下寫法:
```
greet(name) {
/* Assume we have a valid name. */
print('Hi, $name!');
}
```
可以使用塊注釋(/…/)臨時注釋掉一段代碼,但是所有其他注釋都應(yīng)該使用//
### Doc注釋
使用///文檔注釋來記錄成員和類型志电。
使用doc注釋而不是常規(guī)注釋曙咽,可以讓dartdoc找到并生成文檔。
```
/// The number of characters in this chunk when unsplit.
int get length => ...
```
>由于歷史原因挑辆,達(dá)特茅斯學(xué)院支持道格評論的兩種語法:///(“C#風(fēng)格”)和/**…* /(“JavaDoc風(fēng)格”)例朱。我們更喜歡///因為它更緊湊。/**和*/在多行文檔注釋中添加兩個無內(nèi)容的行鱼蝉。在某些情況下洒嗤,///語法也更容易閱讀,例如文檔注釋包含使用*標(biāo)記列表項的項目符號列表魁亦。
###考慮為私有api編寫文檔注釋
Doc注釋并不僅僅針對庫的公共API的外部使用者渔隶。它們還有助于理解從庫的其他部分調(diào)用的私有成員
####用一句話總結(jié)開始doc注釋
以簡短的、以用戶為中心的描述開始你的文檔注釋洁奈,以句號結(jié)尾间唉。
```
/// 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) {
...
}
```
#### “doc注釋”的第一句話分隔成自己的段落
在第一個句子之后添加一個空行绞灼,把它分成自己的段落
```
/// 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) {
...
}
```
## Flutter_Go使用參考
###庫的引用
flutter go中,導(dǎo)入lib下文件庫呈野,統(tǒng)一指定包名镀赌,避免過多的```../../```
```
package:flutter_go/
```
###字符串的使用
####使用相鄰字符串連接字符串文字
如果有兩個字符串字面值(不是值,而是實際引用的字面值)际跪,則不需要使用+連接它們。就像在C和c++中喉钢,簡單地把它們放在一起就能做到姆打。這是創(chuàng)建一個長字符串很好的方法但是不適用于單獨一行。
```
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.');
```
####優(yōu)先使用模板字符串
```
'Hello, $name! You are ${year - birth} years old.';
```
####在不需要的時候肠虽,避免使用花括號
```
'Hi, $name!'
"Wear your wildest $decade's outfit."
```
不推薦如下寫法:
```
'Hello, ' + name + '! You are ' + (year - birth).toString() + ' y...';
```
不推薦如下寫法:
```
'Hi, ${name}!'
"Wear your wildest ${decade}'s outfit."
```
###集合
####盡可能使用集合字面量
如果要創(chuàng)建一個不可增長的列表幔戏,或者其他一些自定義集合類型,那么無論如何税课,都要使用構(gòu)造函數(shù)闲延。
```
var points = [];
var addresses = {};
var lines = [];
```
不推薦如下寫法:
```
var points = List();
var addresses = Map();
```
####不要使用.length查看集合是否為空
```
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(' ');
```
####考慮使用高階方法轉(zhuǎn)換序列
如果有一個集合,并且希望從中生成一個新的修改后的集合韩玩,那么使用.map()垒玲、.where()和Iterable上的其他方便的方法通常更短,也更具有聲明性
```
var aquaticNames = animals
.where((animal) => animal.isAquatic)
.map((animal) => animal.name);
```
####避免使用帶有函數(shù)字面量的Iterable.forEach()
在Dart中找颓,如果你想遍歷一個序列合愈,慣用的方法是使用循環(huán)。
```
for (var person in people) {
...
}
```
不推薦如下寫法:
```
people.forEach((person) {
...
});
```
####不要使用List.from()击狮,除非打算更改結(jié)果的類型
給定一個迭代佛析,有兩種明顯的方法可以生成包含相同元素的新列表
```
var copy1 = iterable.toList();
var copy2 = List.from(iterable);
```
明顯的區(qū)別是第一個比較短。重要的區(qū)別是第一個保留了原始對象的類型參數(shù)
```
// Creates a List:
var iterable = [1, 2, 3];
// Prints "List":
print(iterable.toList().runtimeType);
```
```
// Creates a List:
var iterable = [1, 2, 3];
// Prints "List":
print(List.from(iterable).runtimeType);
```
###參數(shù)的使用
####使用=將命名參數(shù)與其默認(rèn)值分割開
由于遺留原因彪蓬,Dart均允許“:”和“=”作為指定參數(shù)的默認(rèn)值分隔符寸莫。為了與可選的位置參數(shù)保持一致,使用“=”档冬。
```
void insert(Object item, {int at = 0}) { ... }
```
不推薦如下寫法:
```
void insert(Object item, {int at: 0}) { ... }
```
####不要使用顯式默認(rèn)值null
如果參數(shù)是可選的膘茎,但沒有給它一個默認(rèn)值,則語言隱式地使用null作為默認(rèn)值捣郊,因此不需要編寫它
```
void error([String message]) {
stderr.write(message ?? '\n');
}
```
不推薦如下寫法:
```
void error([String message = null]) {
stderr.write(message ?? '\n');
}
```
###變量
####不要顯式地將變量初始化為空
在Dart中辽狈,未顯式初始化的變量或字段自動被初始化為null。不要多余賦值null
```
int _nextId;
class LazyId {
int _id;
int get id {
if (_nextId == null) _nextId = 0;
if (_id == null) _id = _nextId++;
return _id;
}
}
```
不推薦如下寫法:
```
int _nextId = null;
class LazyId {
int _id = null;
int get id {
if (_nextId == null) _nextId = 0;
if (_id == null) _id = _nextId++;
return _id;
}
}
```
####避免儲存你能計算的東西
在設(shè)計類時呛牲,您通常希望將多個視圖公開到相同的底層狀態(tài)刮萌。通常你會看到在構(gòu)造函數(shù)中計算所有視圖的代碼,然后存儲它們:
應(yīng)該避免的寫法:
```
class Circle {
num radius;
num area;
num circumference;
Circle(num radius)
: radius = radius,
area = pi * radius * radius,
circumference = pi * 2.0 * radius;
}
```
如上代碼問題:
-浪費內(nèi)存
-緩存的問題是無效——如何知道何時緩存過期需要重新計算娘扩?
推薦的寫法如下:
```
class Circle {
num radius;
Circle(this.radius);
num get area => pi * radius * radius;
num get circumference => pi * 2.0 * radius;
}
```
###類成員
####不要把不必要地將字段包裝在getter和setter中
不推薦如下寫法:
```
class Box {
var _contents;
get contents => _contents;
set contents(value) {
_contents = value;
}
}
```
####優(yōu)先使用final字段來創(chuàng)建只讀屬性
尤其對于 ```StatelessWidget```
####在不需要的時候不要用this
不推薦如下寫法:
```
class Box {
var value;
void clear() {
this.update(null);
}
void update(value) {
this.value = value;
}
}
```
推薦如下寫法:
```
class Box {
var value;
void clear() {
update(null);
}
void update(value) {
this.value = value;
}
}
```
###構(gòu)造函數(shù)
####盡可能使用初始化的形式
不推薦如下寫法:
```
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);
}
```
####不要使用new
Dart2使new關(guān)鍵字可選
推薦寫法:
```
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!'),
],
);
}
```
###異步
####優(yōu)先使用async/await代替原始的futures
async/await語法提高了可讀性着茸,允許你在異步代碼中使用所有Dart控制流結(jié)構(gòu)壮锻。
```
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;
}
}
```
####當(dāng)異步?jīng)]有任何用處時,不要使用它
如果可以在不改變函數(shù)行為的情況下省略異步涮阔,那么就這樣做猜绣。、
```
Future afterTwoThings(Future first, Future second) {
return Future.wait([first, second]);
}
```
不推薦寫法:
```
Future afterTwoThings(Future first, Future second) async {
return Future.wait([first, second]);
}
```