Just like in the previous project, you are going to create a playground function where every sub-function will demonstrate a different aspect of the strings:
- Type in the following code and use it as the hub for all the other string examples:
void stringPlayground() {
basicStringDeclaration();
multiLineStrings();
combiningStrings();
}
- The first section demonstrates the ways in which you can declare string literals. Write the following function into your code, just under the stringPlayground function:
void basicStringDeclaration() {
// With Single Quotes
print('Single quotes');
final aBoldStatement = 'Dart isn\'t loosely typed.';
print(aBoldStatement);
// With Double Quotes
print("Hello, World");
final aMoreMildOpinion = "Dart's popularity has skyrocketed with
Flutter!";
print(aMoreMildOpinion);
// Combining single and double quotes
final mixAndMatch =
'Every programmer should write "Hello, World" when learning
a new language.';
print(mixAndMatch);
}
- Dart also supports multi-line strings for cases where you have a text block that you want to print to the screen. The following example gets a little Shakespearean:
void multiLineStrings() {
final withEscaping = 'One Fish\nTwo Fish\nRed Fish\nBlue Fish';
print(withEscaping);
final hamlet = '''
To be, or not to be, that is the question:
Whether 'tis nobler in the mind to suffer
The slings and arrows of outrageous fortune,
Or to take arms against a sea of troubles
And by opposing end them.
''';
print(hamlet);
}
- Finally, one of the most common tasks programmers perform with strings is composing them to make more complex strings. Dart supports both the traditional method of concatenation, as well as a more modern method called string interpolation. Type in the following blocks of code to get a feel for both techniques:
void combiningStrings() {
traditionalConcatenation();
modernInterpolation();
}
void traditionalConcatenation() {
final hello = 'Hello';
final world = "world";
final combined = hello + ' ' + world;
print(combined);
}
void modernInterpolation() {
final year = 2011;
final interpolated = 'Dart was announced in $year.';
print(interpolated);
final age = 35;
final howOld = 'I am $age ${age == 1 ? 'year' : 'years'} old.';
print(howOld);
}
- Now, all we have to do to run this code is update main.dart so that it points this file to a new file. Replace the top of main.dart with the following code:
main() {
variablePlayground();
stringPlayground();
}