String in Dart is an immutable sequence of UTF-16 code units. It is an instance of the String class in the dart:core library and serves as the primary data type for textual information.
Internal Representation and Encoding
Dart strings are encoded using UTF-16.- Code Units: The fundamental elements of the string are 16-bit integers.
- Length: The
lengthproperty reflects the number of 16-bit code units. This count may differ from the number of perceived characters (grapheme clusters) if the string contains:- Surrogate Pairs: Characters outside the Basic Multilingual Plane (BMP), such as emojis or certain musical symbols, which require two code units.
- Combining Characters: Diacritics or accents applied to a base character (e.g.,
e+´).
- Runes: The
runesproperty exposes the string as an iterable of Unicode code points.
Immutability
Strings in Dart are immutable. Once a string object is allocated, its content cannot be altered. Methods that appear to modify a string (such assubstring, toLowerCase, or replaceAll) return a new String instance rather than mutating the original.
For mutable character sequences, use the StringBuffer class.
Literal Syntax
Dart provides several syntactic forms for defining string literals.Quoting
String literals may be enclosed in single quotes (') or double quotes ("). Both are functionally identical.
Multi-line Strings
Triple quotes (''' or """) define multi-line strings. These literals preserve newlines and indentation exactly as they appear in the source code.
Raw Strings
Prefixing a string literal withr creates a raw string. In this mode, escape sequences (such as \n or \t) are ignored and treated as literal characters.
String Interpolation
Dart supports string interpolation via the$ syntax, allowing expressions to be evaluated and embedded within a string literal.
- Simple Identifiers:
$variableName - Complex Expressions:
${expression}
toString() method is implicitly invoked on the interpolated object.
Compile-Time Concatenation
Adjacent string literals are automatically concatenated by the compiler. This feature applies strictly to literals, not variables or expressions.Equality
Dart distinguishes between structural equality and identity.- Structural Equality (
==): TheStringclass overrides the==operator to compare the sequence of code units. Two strings are equal if they contain the exact same sequence of UTF-16 code units. - Identity (
identical()): Theidentical()function checks if two references point to the same underlying object.
- Dart VM: Strings are objects. While compile-time constants are interned (canonicalized), dynamically constructed strings with identical content may exist as distinct objects in memory.
- Dart Web (JavaScript): Strings are compiled to JavaScript primitive strings. Because JavaScript treats strings as value types,
identical()behaves effectively the same as==for strings.
Master Dart with Deep Grasping Methodology!Learn More





