Strings

A Dart string is a sequence of UTF-16 code units. You can use eithersingle or double quotes to create a string:

  1. var s1 = 'Single quotes work well for string literals.';
  2. var s2 = "Double quotes work just as well.";
  3. var s3 = 'It\'s easy to escape the string delimiter.';
  4. 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.

  1. var s = 'string interpolation';
  2. assert('Dart has $s, which is very handy.' ==
  3. 'Dart has string interpolation, ' +
  4. 'which is very handy.');
  5. assert('That deserves all caps. ' +
  6. '${s.toUpperCase()} is very handy!' ==
  7. 'That deserves all caps. ' +
  8. '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:

  1. var s1 = 'String '
  2. 'concatenation'
  3. " works even over line breaks.";
  4. assert(s1 ==
  5. 'String concatenation works even over '
  6. 'line breaks.');
  7. var s2 = 'The + operator ' + 'works, as well.';
  8. 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:

  1. var s1 = '''
  2. You can create
  3. multi-line strings like this one.
  4. ''';
  5. var s2 = """This is also a
  6. multi-line string.""";

You can create a “raw” string by prefixing it with r:

  1. 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.

  1. // These work in a const string.
  2. const aConstNum = 0;
  3. const aConstBool = true;
  4. const aConstString = 'a constant string';
  5. // These do NOT work in a const string.
  6. var aNum = 0;
  7. var aBool = true;
  8. var aString = 'a string';
  9. const aConstList = [1, 2, 3];
  10. const validConstString = '$aConstNum $aConstBool $aConstString';
  11. // const invalidConstString = '$aNum $aBool $aString $aConstList';

For more information on using strings, seeStrings and regular expressions.