Dart: Spread operator (…)

最近在寫flutter app程式時,發現一個dart奇特的語法:

children: [
                  ...[
                    "Toys",
                    "Appliances",
                    "Tools",
                    "Food",
                  ].map((e) {
                    return _CardButton(
                      label: e,
                      onPressed: () => onCategorySelected(e),
                    );
                  }).toList()
                ],

 

這...特殊運算子是"展開運算子" Spread operator ,  from Dart 2.3

    var a = [0,1,2,3,4];
    var b = [6,7,8,9];
    var c = [...a,5,...b];

    print(c);  // prints: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
就是他會自動擴展之後的陣列資料.可以輕鬆地將兩個 List 結合在一起.
有點像concat function:
nums = [].concat(digitBuckets);
nums = [].addAll(digitBucketsd);
很複雜,不容易理解.
.
在flutter很常看到別人這樣用:
For Flutter, we can use this inside column
List<String> values = [ 'one', 'two', 'three' ];
 Column(
          children: [
            ...values.map((value) {
              return Text(value);
            }),
          ],
        ),

output:





--
而且他還有 null-aware spread operator (...?), 
which allows us to add multiple elements in Collections.
  List<String> values1 = ['one', 'two', 'three'];
  List<String> values2 = ['four', 'five', 'six'];
  var output = [...values1,...values2];
  print(output); // [one, two, three, four, five, six]

------
除此之外, dart還有個類似的運算子: Double dot (..) operator 

Cascade Operator

兩個點的.cascade notation. 一般來說,在其他語言,下面這樣寫是錯誤的.(X) 
Error: This expression has type 'void' and can't be used.
void main() {
 List<int> list= []; 
  list.add(1).add(2).add(3);
  print (list);
}
---
但是如果改成用dart cascade notation:
List coursename;
coursename..add("java")..add("flutter" )..add("dart");
就樣就可以了.

又如下面之範例:
// sample code that does not make use of cascade operator
void noCascade() {
  var sb = StringBuffer();
  sb.write('hello\n');
  sb.write('world!\n');
  sb.write('a\n');
  sb.write('b\n');
  sb.write('c\n');
  sb.write('d\n');
  sb.write('e\n');
  print(sb.toString());
}

// sample code that makes use of cascade operator
void cascade() {
  print((StringBuffer()
        ..write('hello\n')
        ..write('world!\n')
        ..write('a\n')
        ..write('b\n')
        ..write('c\n')
        ..write('d\n')
        ..write('e\n'))
      .toString());
}

cascade operator也用來可串接不同指令:
getAddress()
 ..setStreet(“Elm”, “13a”)
 ..city = “Carthage”
 ..state = “Eurasia”
 ..zip(66666, extended: 6666);
變得更簡潔.所以就是Dart增加了一些語法,方便開發者使用.


留言

這個網誌中的熱門文章

最爛的銀行服務-玉山銀行

Mark App Design Apps - Terms and Privacy Policy (服務條款,隱私權政策)

SMR疊瓦式hdd致命缺陷被解決????!!!

ios app 上架時app icon要注意事項

更改google drive預設存放目錄位置Change Google Drive Default Folder Location in Windows

舊有app在Android 12 閃退問題& app Splash screens

google play 正式發布前測試報告...非常好用.

app bundle and bundletool. 關於aab安裝問題

關於google play console app應用程式簽署

Google Play badge徽章產生器