Strings
A Dart string is a sequence of UTF-16 code units. You can use eithersingle or double quotes to create a string:
var s1 = 'Single quotes work well for string literals.';
var s2 = "Double quotes work just as well.";
var s3 = 'It\'s easy to escape the string delimiter.';
var s4 = "It's even easier to use the other delimiter.";
You can put the value of an expression inside a string by using${
expression
}
. If the expression is an identifier, you can skipthe {}. To get the string corresponding to an object, Dart calls theobject’s toString()
method.
var s = 'string interpolation';
assert('Dart has $s, which is very handy.' ==
'Dart has string interpolation, ' +
'which is very handy.');
assert('That deserves all caps. ' +
'${s.toUpperCase()} is very handy!' ==
'That deserves all caps. ' +
'STRING INTERPOLATION is very handy!');
Note: The ==
operator tests whether two objects are equivalent. Two strings are equivalent if they contain the same sequence of code units.
You can concatenate strings using adjacent string literals or the +
operator:
var s1 = 'String '
'concatenation'
" works even over line breaks.";
assert(s1 ==
'String concatenation works even over '
'line breaks.');
var s2 = 'The + operator ' + 'works, as well.';
assert(s2 == 'The + operator works, as well.');
Another way to create a multi-line string: use a triple quote witheither single or double quotation marks:
var s1 = '''
You can create
multi-line strings like this one.
''';
var s2 = """This is also a
multi-line string.""";
You can create a “raw” string by prefixing it with r
:
var s = r'In a raw string, not even \n gets special treatment.';
See Runes and grapheme clusters for details on howto express Unicode characters in a string.
Literal strings are compile-time constants,as long as any interpolated expression is a compile-time constantthat evaluates to null or a numeric, string, or boolean value.
// These work in a const string.
const aConstNum = 0;
const aConstBool = true;
const aConstString = 'a constant string';
// These do NOT work in a const string.
var aNum = 0;
var aBool = true;
var aString = 'a string';
const aConstList = [1, 2, 3];
const validConstString = '$aConstNum $aConstBool $aConstString';
// const invalidConstString = '$aNum $aBool $aString $aConstList';
For more information on using strings, seeStrings and regular expressions.