[TOC]
以下是在Dart中編寫字符串時需要記住的一些最佳實踐。
## 使用相鄰字符串連接字符串文字。
如果有兩個字符串字面值(不是值,而是實際引用的字面值),則不需要使用+連接它們。就像在C和c++中,簡單地把它們放在一起就能做到。這是創建一個長字符串很好的方法但是不適用于單獨一行。
~~~
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.');
~~~
## 優先使用插值來組合字符串和值。
如果您之前是用其他語言做開發的,那么您習慣使用+的長鏈來構建文字和其他值的字符串。 這在Dart中有效,但使用插值總是更清晰,更簡短:
~~~
'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."
~~~