Dart from the ground up

Text, interpolation and formatting

Joining text with the plus sign, dropping values into a string with a dollar sign, and turning a number into the wording you want with toStringAsFixed.

Part 3 of 12

Beginner15 min readBack to Courses

Two ways to build a line of text

Text in double quotes is a String, and the plus sign joins two Strings into a longer one. The trouble is that Dart will not join a String to a number: "Total: " + 50.0 is an error, so the number has to be turned into text first with .toString().

The shorter way is interpolation. A dollar sign inside a string pulls a value into the text: "Hello, $name!" or "Item: $name x $count". There is no plus sign and no toString, because the compiler writes it for you. Both forms produce exactly the same characters, so choose interpolation and reach for the plus sign only when a line is easier to read that way.

Braces, when a name is not enough

A bare $name works for a single name. The moment you want a calculation instead — a sum, a call, a property read — wrap it in braces, and the whole thing is worked out before it lands in the text.

Everything between the braces is ordinary Dart, so a length or a division can sit inside a sentence. The snippet below shows both forms. A missing closing brace is one of the few mistakes whose message is worth reading twice, so count the two braces as you type them.

Making a number say what you mean

A double prints in its own plain form: 12.5 prints as 12.5 and 32.0 prints as 32.0. Money usually wants two decimal places, and toStringAsFixed(2) gives you that: 32 becomes 32.00. The number is rounded to that many decimal places, and the result is a String you can print or join.

Strings also carry their own useful methods. .length counts the characters, .toUpperCase() and .toLowerCase() change the case, .contains("u") answers whether a piece of text is in there, and .trim() removes spaces from both ends — handy for tidying something a person typed.

Escapes: characters you cannot type directly

Inside double quotes, a backslash gives the next character a second meaning. \n is a line break, \t is a tab, \" is a quote that belongs to the text rather than ending it, and \\ is one backslash. A price line with \t between its columns lines up without counting spaces.

A dollar sign also needs the backslash when you want the character rather than a value: "\$5" prints a dollar sign and a five. The same escape works inside interpolation, which is how a lesson can show the syntax without the compiler filling it in.

When a string has many backslashes — a Windows path, a regular expression — put r in front and the string is raw: r"C:\notes" keeps every character as typed. A raw string cannot interpolate, because the dollar sign there is only a dollar sign.

Splitting, slicing and padding

A String is a sequence of characters, and the methods that read it do not change it. split(",") cuts at each comma and gives a list of pieces. substring(0, 3) takes the characters from position 0 up to but not including 3. replaceAll(" ", "_") returns a new string with every match replaced.

padLeft(6) and padRight(10) add spaces until the text reaches a given width, which is all a plain-text column needs. padLeft(6, "0") fills with zeros instead, which is how a cents value becomes "05".

Counting starts at zero, as it does in a list, so the first character sits at position 0. Asking for a range that runs past the end throws, so check .length when the text came from somewhere you do not control.

Interpolation and a fixed number of decimals

void main() {
  final item = "Hub";
  final cents = 3200;
  print("Item: $item");
  print("Cost: ${cents / 100}");
  print("Fixed: ${(cents / 100).toStringAsFixed(2)}");
  print("Has u: ${item.contains("u")}");
}

A receipt line, built three ways

Run it and read the two Total lines. Then change the count and the price, add a line that prints the item in lower case, and add one that shows the item length inside a sentence.

Output
Click "Run" to execute your code

Three mistakes with text. Forgetting to escape a dollar sign you want to print, so the compiler looks for a name that is not there. Writing "$name.length" and expecting the length, when the bare name ends at the dot and the text ".length" is printed after it — braces are what make the whole expression part of the interpolation. And joining a number to text with + without calling .toString().

Try these next

  • Build one line with a tab between two columns and another with padRight, then compare how they line up.
  • Split "hub,3200" at the comma, print each part on its own line, then print the second part plus 100 as a number.
  • Print a string containing a quote, a backslash and a dollar sign, each escaped so it appears as typed.

A plain-text table from split and pad

Run it and check that the cents column lines up under its heading. Then add a fourth row, change the trim example to a name with two spaces inside, and print the result of splitting that name.

Output
Click "Run" to execute your code

Read the two Total lines in the example: one is written with interpolation and one with the plus sign. They print the same characters, so the shorter form is a matter of taste rather than of power.

Check what you learned

One question at a time. A wrong answer explains itself — take another go.

Part 1 of 5

When do you need braces around a value inside a string?