從零件建造

以程式設計方式生成 String 最好使用 StringBuffer 完成。在呼叫 toString() 之前,StringBuffer 不會生成新的 String 物件。

var sb = new StringBuffer();

sb.write("Use a StringBuffer");
sb.writeAll(["for ", "efficient ", "string ", "creation "]);
sb.write("if you are ")
sb.write("building lots of strings");

// or you can use method cascades:

sb
  ..write("Use a StringBuffer")
  ..writeAll(["for ", "efficient ", "string ", "creation "])
  ..write("if you are ")
  ..write("building lots of strings");

var fullString = sb.toString();

print(fullString); 
// Use a StringBufferfor efficient string creation if you are building lots of strings

sb.clear(); // all gone!