TExcelTAD
Home › Flutter › Dart Strings

Dart Strings

A String is a sequence of characters such as a name, a message or a line of JSON. In Flutter you'll display strings in Text widgets, read them from text fields and build them from data — so strings are worth knowing well.

Creating strings

dart · try it yourself
void main() {
  var single = 'Single quotes';
  var doubleQuoted = "Double quotes work too";
  var escaped = 'It\'s easy';
  var mixed = "It's easier";
  var raw = r'Raw: \n is not a newline here';

  var multi = '''
Line one
Line two''';

  print(single);
  print(doubleQuoted);
  print(escaped);
  print(mixed);
  print(raw);
  print(multi);
}
Single quotes
Double quotes work too
It's easy
It's easier
Raw: \n is not a newline here
Line one
Line two
  • Use \' or the other quote style to include a quote character.
  • A r prefix creates a raw string where backslashes are not escapes.
  • Triple quotes (''' or """) span multiple lines.

Interpolation and concatenation

$variable inserts a value; ${expression} inserts the result of any expression. Adjacent string literals are joined automatically, which is handy for long text.

dart · try it yourself
void main() {
  var user = 'minh';
  var cartItems = 3;
  var price = 12.5;

  print('Hi $user!');
  print('Hi ${user.toUpperCase()}!');
  print('Total: ${cartItems * price} USD');
  print('Hello, ' + user);

  var long = 'Adjacent literals '
      'are concatenated '
      'at compile time.';
  print(long);
}
Hi minh!
Hi MINH!
Total: 37.5 USD
Hello, minh
Adjacent literals are concatenated at compile time.

Tip: Prefer interpolation over +. The Dart linter even flags 'a' + b and suggests 'a$b'.

Common properties and methods

Strings are immutable: methods never change the original, they return a new string.

Member Result
length Number of UTF-16 code units
isEmpty / isNotEmpty Whether the string has characters
toUpperCase() / toLowerCase() Changed case
trim() Without leading/trailing whitespace
contains(x) true if x occurs
startsWith(x) / endsWith(x) Prefix/suffix test
indexOf(x) Position of x, or -1
substring(start, [end]) Part of the string
replaceAll(a, b) Every a replaced with b
split(sep) A List<String>
padLeft(n, ch) Padded to width n
dart · try it yourself
void main() {
  var text = '  Flutter makes apps  ';
  var clean = text.trim();

  print(clean);
  print(clean.length);
  print(clean.toUpperCase());
  print(clean.contains('apps'));
  print(clean.startsWith('Flu'));
  print(clean.indexOf('makes'));
  print(clean.substring(0, 7));
  print(clean.replaceAll('apps', 'UIs'));
  print(clean.split(' '));
  print('7'.padLeft(3, '0'));
  print(clean[0]);
}
Flutter makes apps
18
FLUTTER MAKES APPS
true
true
8
Flutter
Flutter makes UIs
[Flutter, makes, apps]
007
F

Use square brackets s[i] to read a single character (as a one-character string). Indexes start at 0.

Building strings efficiently

If you build a long string piece by piece — for example inside a loop — use a StringBuffer. It avoids creating a new string object for every step.

dart · try it yourself
void main() {
  var sb = StringBuffer();
  for (var i = 1; i <= 5; i++) {
    sb.write(i);
    if (i < 5) sb.write(' -> ');
  }
  print(sb.toString());

  // join is often even simpler
  var words = ['red', 'green', 'blue'];
  print(words.join(', '));
}
1 -> 2 -> 3 -> 4 -> 5
red, green, blue

Comparing strings

== compares contents, and compareTo gives alphabetical order (negative, zero or positive). For case-insensitive comparison, lowercase both sides first.

dart · try it yourself
void main() {
  print('apple' == 'apple');
  print('Apple' == 'apple');
  print('Apple'.toLowerCase() == 'apple');
  print('apple'.compareTo('banana'));
  print('pear'.compareTo('fig'));
}
true
false
true
-1
1

Test yourself

What does 'abc'.toUpperCase() do to the original string?

  1. Changes it to 'ABC'
  2. Nothing — it returns a new string
  3. Throws an error
  4. Changes only the first letter

Which string prints a literal backslash followed by n?

  1. '\n'
  2. r'\n'
  3. "\n"
  4. '''\n'''

What is 'Dart'.substring(1, 3)?

  1. 'Da'
  2. 'ar'
  3. 'art'
  4. 'Dar'