A String is used to store text, such as names, messages, and sentences. In Dart, strings are sequences of UTF-16 code units. You can define them using either single quotes (' ') or double quotes (" "), providing flexibility for including special characters like apostrophes or speech marks.
1. Declaration and Basic Usage
Every string variable in Dart is an object of the String class. This means even a simple text variable has access to powerful properties and methods.
Variable Declaration
1// Declare a string variable2String name = 'houssam';3print('Name: $name');4 5// Strings can contain numbers or symbols as text6String zipCode = '12345';7String currency = "$";HintVariables are declared using the String keyword followed by the variable name and a value in quotes.
2. Combining Strings: Concatenation vs. Interpolation
There are two primary ways to join text together. While the + operator is common in many languages, Dart strongly encourages interpolation for cleaner code.
Joining Text
1String name = 'houssam';2 3// Method A: Concatenation using +4String greeting = 'Hello, ' + name + '!';5print(greeting);6 7// Method B: Interpolation using $ (Recommended)8print('Hello again, $name!');9 10// Expression Interpolation11// Use curly braces for calculations or logic inside strings12print('Name Length: ${name.length}');HintConcatenation joins strings together using +, while interpolation inserts variable values directly into a string using the $ symbol.
3. Essential String Methods
Dart provides a rich set of built-in methods to transform and analyze your text data without changing the original variable (strings are immutable).
Common Transformations
1String message = 'Dart is Fun';2 3print(message.toUpperCase()); // Output: DART IS FUN4print(message.toLowerCase()); // Output: dart is fun5print('Length: ${message.length}'); // Output: 116print('Substring: ${message.substring(0, 4)}'); // Output: Dart7print('Contains Dart: ${message.contains("Dart")}'); // trueHintThe length property returns the number of characters, while substring(start, end) extracts a specific range of text.
4. Handling Quotes and Escape Characters
If you need to use a quote inside a string, you can either alternate quote types (single vs double) or use a backslash () as an escape character.
Correct Way to Handle Quotes
1// Using different quote types2print("This is 'valid'");3print('He said: "Nice!"');4 5// Using escape characters6print('It\'s a great day!');7print("He said: \"Flutter is awesome!\"");HintThe backslash tells Dart to ignore the special meaning of the quote and treat it as literal text.
5. Common Errors and "Gotchas"
Understanding where things go wrong is just as important as knowing how they work. Here are two common pitfalls in Dart.
Type Mismatches and Unescaped Strings
1int age = 22;2 3// ❌ ERROR: Mixing String and int directly using +4// print('My score is: ' + 100);5 6// ✅ CORRECT: Convert to string first7print('Age: ' + age.toString());8print('Age: $age'); // Better approach9 10// ❌ ERROR: Unescaped quote inside string11// print('This is "wrong); // Error: unterminated stringHintDart is type-safe; you cannot add an integer to a string using + without explicit conversion or interpolation.
Loot collected
Key takeaways- Strings store text and are defined using single or double quotes.
- String interpolation ($variable) is the preferred way to combine text and variables.
- Concatenation (+) only works when both sides are already Strings; otherwise, use .toString().
- Use escape characters () to include protected symbols like quotes inside your text.
- String methods like toUpperCase() and substring() provide powerful ways to manipulate text.
Side quests
Practice exercises
Exercise 1: Personal Greeting
Create a string variable for your favorite color. Combine your name and that color into a single sentence using interpolation.
Reveal solutionHide solution
1String color = 'Blue'; String name = 'Houssam'; print('My name is $name and my favorite color is $color');Exercise 2: Data Extraction
Given the string "FLUTTER_DEVELOPER", use a method to extract only the word "FLUTTER" and convert it to lowercase.
Reveal solutionHide solution
1String role = 'FLUTTER_DEVELOPER'; print(role.substring(0, 7).toLowerCase());Exercise 3: Fixing Errors
Fix this code: print("The price is: " + 50);
Reveal solutionHide solution
1print('The price is: ${50}'); or print('The price is: ' + 50.toString());