Flutter 代碼開發(fā)規(guī)范

一、代碼風(fēng)格

1、標(biāo)識(shí)符三種類型

大駝峰

類、枚舉、typedef和類型參數(shù)

  class SliderMenu { ... }
  
  class HttpRequest { ... }
  
  typedef Predicate = bool Function<T>(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)識(shí)符

  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();
  }

不使用前綴字母

因?yàn)镈art可以告訴您聲明的類型、范圍、可變性和其他屬性,所以沒有理由將這些屬性編碼為標(biāo)識(shí)符名稱。

  defaultTimeout

不推薦如下寫法:

  kDefaultTimeout

2、排序

為了使你的文件前言保持整潔,我們有規(guī)定的命令,指示應(yīng)該出現(xiàn)在其中。每個(gè)“部分”應(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ú)的部分中指定導(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';

3、所有流控制結(jié)構(gòu),請使用大括號(hào)

這樣做可以避免懸浮的else問題

  if (isWeekDay) {
    print('Bike to work!');
  } else {
    print('Go dancing or read a book!');
  }

例外

一個(gè)if語句沒有else子句,其中整個(gè)if語句和then主體都適合一行。在這種情況下,如果你喜歡的話,你可以去掉大括號(hào)

  if (arg == null) return defaultValue;

如果流程體超出了一行需要分劃請使用大括號(hào):

  if (overflowChars != other.overflowChars) {
    return overflowChars < other.overflowChars;
  }

不推薦如下寫法:

  if (overflowChars != other.overflowChars)
    return overflowChars < other.overflowChars;

二、注釋

1、要像句子一樣格式化

除非是區(qū)分大小寫的標(biāo)識(shí)符,否則第一個(gè)單詞要大寫。以句號(hào)結(jié)尾(或“!”或“?”)。對于所有的注釋都是如此:doc注釋、內(nèi)聯(lián)內(nèi)容,甚至TODOs。即使是一個(gè)句子片段。

  greet(name) {
    // Assume we have a valid name.
    print('Hi, $name!');
  }

不推薦如下寫法:

  greet(name) {
    /* Assume we have a valid name. */
    print('Hi, $name!');
  }

可以使用塊注釋(/…/)臨時(shí)注釋掉一段代碼,但是所有其他注釋都應(yīng)該使用//

2、Doc注釋

使用///文檔注釋來記錄成員和類型。

使用doc注釋而不是常規(guī)注釋,可以讓dartdoc找到并生成文檔。

  /// The number of characters in this chunk when unsplit.
  int get length => ...

由于歷史原因,達(dá)特茅斯學(xué)院支持道格評(píng)論的兩種語法:///(“C#風(fēng)格”)和/ /(“JavaDoc風(fēng)格”)。我們更喜歡/// 因?yàn)樗o湊。//在多行文檔注釋中添加兩個(gè)無內(nèi)容的行。在某些情況下,///語法也更容易閱讀,例如文檔注釋包含使用*標(biāo)記列表項(xiàng)的項(xiàng)目符號(hào)列表。

3、考慮為私有api編寫文檔注釋

Doc注釋并不僅僅針對庫的公共API的外部使用者。它們還有助于理解從庫的其他部分調(diào)用的私有成員

用一句話總結(jié)開始doc注釋

以簡短的、以用戶為中心的描述開始你的文檔注釋,以句號(hào)結(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注釋”的第一句話分隔成自己的段落

在第一個(gè)句子之后添加一個(gè)空行,把它分成自己的段落

  /// 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 使用參考

1、庫的引用

flutter go 中,導(dǎo)入lib下文件庫,統(tǒng)一指定包名,避免過多的../../

package:flutter_go/

2、字符串的使用

使用相鄰字符串連接字符串文字

如果有兩個(gè)字符串字面值(不是值,而是實(shí)際引用的字面值),則不需要使用+連接它們。就像在C和c++中,簡單地把它們放在一起就能做到。這是創(chuàng)建一個(gè)長字符串很好的方法但是不適用于單獨(dú)一行。

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.';

在不需要的時(shí)候,避免使用花括號(hào)

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

不推薦如下寫法:

  'Hello, ' + name + '! You are ' + (year - birth).toString() + ' y...';

不推薦如下寫法:

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

3、集合

盡可能使用集合字面量

如果要?jiǎng)?chuàng)建一個(gè)不可增長的列表,或者其他一些自定義集合類型,那么無論如何,都要使用構(gòu)造函數(shù)。

  var points = [];
  var addresses = {};
  var lines = <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)換序列

如果有一個(gè)集合,并且希望從中生成一個(gè)新的修改后的集合,那么使用.map()、.where()和Iterable上的其他方便的方法通常更短,也更具有聲明性

  var aquaticNames = animals
      .where((animal) => animal.isAquatic)
      .map((animal) => animal.name);

避免使用帶有函數(shù)字面量的Iterable.forEach()

在Dart中,如果你想遍歷一個(gè)序列,慣用的方法是使用循環(huán)。

for (var person in people) {
  ...
}

不推薦如下寫法:

  people.forEach((person) {
    ...
  });

不要使用List.from(),除非打算更改結(jié)果的類型

給定一個(gè)迭代,有兩種明顯的方法可以生成包含相同元素的新列表

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

明顯的區(qū)別是第一個(gè)比較短。重要的區(qū)別是第一個(gè)保留了原始對象的類型參數(shù)

// Creates a List<int>:
var iterable = [1, 2, 3];

// Prints "List<int>":
print(iterable.toList().runtimeType);
// Creates a List<int>:
var iterable = [1, 2, 3];

// Prints "List<dynamic>":
print(List.from(iterable).runtimeType);

4、參數(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ù)是可選的,但沒有給它一個(gè)默認(rèn)值,則語言隱式地使用null作為默認(rèn)值,因此不需要編寫它

void error([String message]) {
  stderr.write(message ?? '\n');
}

不推薦如下寫法:

void error([String message = null]) {
  stderr.write(message ?? '\n');
}

5、變量

不要顯式地將變量初始化為空

在Dart中,未顯式初始化的變量或字段自動(dòng)被初始化為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;
    }
  }

避免儲(chǔ)存你能計(jì)算的東西

在設(shè)計(jì)類時(shí),您通常希望將多個(gè)視圖公開到相同的底層狀態(tài)。通常你會(huì)看到在構(gòu)造函數(shù)中計(jì)算所有視圖的代碼,然后存儲(chǔ)它們:

應(yīng)該避免的寫法:

  class Circle {
    num radius;
    num area;
    num circumference;
  
    Circle(num radius)
        : radius = radius,
          area = pi * radius * radius,
          circumference = pi * 2.0 * radius;
  }

如上代碼問題:

  • 浪費(fèi)內(nèi)存
  • 緩存的問題是無效——如何知道何時(shí)緩存過期需要重新計(jì)算?

推薦的寫法如下:

  class Circle {
    num radius;
  
    Circle(this.radius);
  
    num get area => pi * radius * radius;
    num get circumference => pi * 2.0 * radius;
  }

5、類成員

不要把不必要地將字段包裝在getter和setter中

不推薦如下寫法:

  class Box {
    var _contents;
    get contents => _contents;
    set contents(value) {
      _contents = value;
    }
  }

優(yōu)先使用final字段來創(chuàng)建只讀屬性

尤其對于 StatelessWidget

在不需要的時(shí)候不要用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;
    }
  }

6、構(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!'),
      ],
    );
  }

7、異步

優(yōu)先使用async/await代替原始的futures

async/await語法提高了可讀性,允許你在異步代碼中使用所有Dart控制流結(jié)構(gòu)。

  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;
    }
  }

當(dāng)異步?jīng)]有任何用處時(shí),不要使用它

如果可以在不改變函數(shù)行為的情況下省略異步,那么就這樣做。、

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

不推薦寫法:

  Future afterTwoThings(Future first, Future second) async {
    return Future.wait([first, second]);
  }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 默認(rèn)參數(shù) 默認(rèn)參數(shù)很有用,但使用不當(dāng),也會(huì)掉坑里。默認(rèn)參數(shù)有個(gè)最大的坑,演示如下: 先定義一個(gè)函數(shù),傳入一個(gè)lis...
    沙灘印閱讀 82評(píng)論 0 0
  • 一、Python簡介和環(huán)境搭建以及pip的安裝 4課時(shí)實(shí)驗(yàn)課主要內(nèi)容 【Python簡介】: Python 是一個(gè)...
    _小老虎_閱讀 6,338評(píng)論 0 10
  • sqli-labs(1-10) -- (這里有一個(gè)空格,--空格)在SQL內(nèi)表示注釋,但在URL中,如果在最后加上...
    glotozz閱讀 312評(píng)論 0 0
  • 軟件測試基礎(chǔ)知識(shí)01—軟件缺陷 1.軟件缺陷(Bug)的定義 定義:被測軟件(系統(tǒng))中存在破壞其正常運(yùn)行能力的問題...
    SHARE李閱讀 744評(píng)論 0 1
  • 過去生活困難,都為逢年過節(jié)走親訪友犯愁,條件好點(diǎn)的家庭就買點(diǎn)油炸裹(油條),用紙攆子繩捆著6股油條挨家逐戶的出門。...
    高崖小秦閱讀 527評(píng)論 0 1

友情鏈接更多精彩內(nèi)容