Dart: Working with String type

Arte Bi
3 min readAug 22, 2023

--

This article is part of a series on How to start creating mobile applications for Android or iOS using Dart & Flutter.

Photo by Patrick Fore on Unsplash

Creation

In Dart, a string is a sequence of characters enclosed in either single or double quotes.

String singleQuoted = 'This is a single-quoted string.';
String doubleQuoted = "This is a double-quoted string.";

If you want to create multi-line strings, you can use triple single or double quotes.

String multiLineSingleQuoted = '''
line 1
line 2
''';

String multiLineDoubleQuoted = """
line 1
line 2
""";

Remember that Dart strings are immutable, which means once you create a string, you cannot modify it directly. If you need to modify strings, you’ll create new ones based on the existing ones.

Сoncatenation

You can do сoncatenation using the (+) operator or using string interpolation with (${}).

String firstName = 'John';
String lastName = 'Doe';
String fullName = firstName + ' ' + lastName; // Concatenating strings
print(fullName); // Output: John Doe

String interpolation is a way to embed expressions within strings using (${}). Dart evaluates the expressions and replaces them with their values in the resulting string.

String fruit = "apple";
int quantity = 3;
String message = "I have $quantity ${fruit}s."; // Using string interpolation
print(message); // Output: I have 3 apples.

String interpolation is often more concise and readable, especially when dealing with complex expressions.

int length = 5;
int width = 3;
String areaMessage = "The area is ${length * width} square units.";
print(areaMessage); // Output: The area is 15 square units.

Including complex expressions within ({}) is advised. For simpler cases, curly braces are not necessary.

String name = 'Adam';
int ageInMonths = 78;
print('Name: $name, age: ${ageInMonths / 12}'); // Output: Name: Adam, age: 6.5

Escaping characters

Escaping characters involves using special codes to represent characters that have a special meaning, like newlines or quotation marks, within strings. This prevents the compiler from misinterpreting these characters. You can escape characters using a backslash (\) before the character you want to escape. A few common examples are below.

Newline \n represents a new line within a string.

String multiLine = "First line.\nSecond line.";
print(multiLine);
// Output:
// First line.
// Second line.

Tab \t represents a tab character within a string.

String indented = "Indented\ttext.";
print(indented); // Output: Indented text.

Double Quote \” represents a double quotation mark within a double-quoted string.

String quoted = "She said, \"Hello!\"";
print(quoted); // Output: She said, "Hello!"

String Methods

Dart provides a variety of string methods that you can use to manipulate and work with strings. Here are some common string methods in Dart.

length: Returns the length (number of characters) of the string.

String text = "Hello, world!";
int length = text.length; // length is 13

toUpperCase() and toLowerCase(): Converts the string to uppercase or lowercase.

String message = "Hello, Dart!";
String upper = message.toUpperCase(); // "HELLO, DART!"
String lower = message.toLowerCase(); // "hello, dart!"

isEmpty and isNotEmpty: Checks if the string is empty or not.

String emptyString = "";
bool isEmpty = emptyString.isEmpty; // true
bool isNotEmpty = emptyString.isNotEmpty; // false

split(): Splits the string into a list of substrings based on a delimiter.

String names = "Alice, Bob, Carol, Dave";
List<String> nameList = names.split(", "); // ["Alice", "Bob", "Carol", "Dave"]

Working with Characters

You can get a character from a string using the square bracket ([]) operator along with an index number. The index represents the position of the character you want to retrieve within the string.

String myString = "Hello, Dart!";

// Getting characters using index
var firstCharacter = myString[0]; // Gets the first character 'H'
var fifthCharacter = myString[5]; // Gets the sixth character ','
var lastCharacter = myString[11]; // Gets the last character '!'

Remember that the index starts from 0 for the first character, 1 for the second, and so on. If you try to access an index that is out of bounds (greater than or equal to the string length), you'll get an "index out of range" error.

--

--