On top of simply declaring strings, the more common use of this data type is to concatenate multiple values to build complex statements. Dart supports the traditional way of concatenating strings; that is, by simply using the addition (+) symbol between multiple strings, like so:
final sum = 1 + 1; // 2
final concatenate = 'one plus one is ' + sum;
While Dart fully supports this method of constructing strings, the language also supports interpolation syntax. The second statement can be updated to look like this:
final sum = 1 + 1;
final interpolate = 'one plus one is $sum'
The dollar sign notation only works for single values, such as the integer in the preceding snippet. If you need anything more complex, you can add curly brackets after the dollar sign and write any Dart expression. This can range from something simple, such as accessing a member of a class, to a complex ternary operator.
Let's break down the following example:
final age = 35;
final howOld = 'I am $age ${age == 1 ? 'year' : 'years'} old.';
print(howOld);
The first line declares an integer called age and sets its value to 35. The second line contains both types of string interpolation. First, the value is just inserted with $age, but after that, there is a ternary operator inside the string to determine whether the word year or years should be used:
age == 1 ? 'year' : 'years'
This statement means that if the value of age is 1, then use the singular word year; otherwise, use the plural word years. When you run this code, you'll see the following output:
I am 35 years old.
Over time, this will become natural. Just remember that legible code is usually better than shorter code, even if it takes up more space.
It's probably worth mentioning another way to perform concatenation tasks, which is using the StringBuffer object. Consider the following code:
List fruits = ['Strawberry', 'Coconut', 'Orange', 'Mango', 'Apple'];
StringBuffer buffer = StringBuffer();
for (String fruit in fruits) {
buffer.write(fruit);
buffer.write(' ');
}
print (buffer.toString()); // prints: Strawberry Coconut Orange Mango Apple
You can use a StringBuffer to incrementally build a string. This is better than using string concatenation as it performs better. You add content to a StringBuffer by calling its write method. Then, once it's been created, you can transform it into a String with the toString method.