Strings & Numbers
Text Magic and Math Power
Open interactive version (quiz + challenge)Real-world analogy
Strings are like friendship bracelets made of letter beads -- you can combine them, split them, find specific beads, and rearrange them. Numbers are like a calculator -- you can add, subtract, multiply, divide, and do all sorts of math. Together, they are the most common types of data you will ever work with!
What is it?
Strings hold text and have powerful methods for searching, transforming, and combining text. String interpolation ($variable) lets you embed values inside strings. Numbers include int (whole) and double (decimal) with full arithmetic support. Dart also provides dart:math for advanced math operations.
Real-world relevance
String manipulation is everywhere: displaying user names, formatting prices, parsing API responses, validating email addresses. Number operations handle everything from shopping cart totals to game scores to GPS coordinates. These are the building blocks of every app.
Key points
- String Interpolation with $ — Use $variableName inside a string to insert a variable's value. For expressions, use ${expression}. This is much cleaner than joining strings with the + operator. Dart developers use interpolation everywhere.
- Multiline Strings — Use triple quotes (single or double) to write strings that span multiple lines. This is great for long text, JSON templates, or formatted output. The line breaks are preserved in the output.
- String Methods — Strings have many built-in methods: toUpperCase(), toLowerCase(), trim(), split(), contains(), startsWith(), endsWith(), replaceAll(), substring(), padLeft(), and more. These let you transform and search text easily.
- Substring and IndexOf — substring() extracts part of a string by position. indexOf() finds where a character or word first appears. Together, they let you locate and extract specific parts of text, like finding a username in an email.
- Arithmetic Operators — Dart supports +, -, *, / (division returns double), ~/ (integer division), and % (remainder/modulo). These work on int and double. Integer division (~/) is unique to Dart -- it divides and rounds down to a whole number.
- Number Parsing and Conversion — Convert strings to numbers with int.parse() and double.parse(). Convert numbers to strings with .toString() and .toStringAsFixed(). Use tryParse() for safe parsing that returns null instead of crashing on bad input.
- Math Operations — The dart:math library provides advanced math: sqrt(), pow(), min(), max(), and the Random class. Import it with 'import dart:math;' to access these tools.
- Number Properties — Numbers have useful properties: isEven, isOdd, isNegative, isNaN, isFinite, isInfinite. These return true or false and help you check number characteristics without writing comparison logic yourself.
- String Comparison and Equality — Compare strings with == (equal) and != (not equal). Use compareTo() for alphabetical ordering. String comparison in Dart is case-sensitive, so 'Hello' and 'hello' are NOT equal.
Code example
import 'dart:math';
void main() {
// String interpolation
var name = 'Flutter';
var version = 3;
print('Welcome to $name $version!');
print('Name has ${name.length} letters');
// String methods
var email = 'User@Example.COM';
print(email.toLowerCase()); // user@example.com
print(email.contains('@')); // true
print(email.split('@')); // [User, Example.COM]
// Multiline string
var message = '''
Dear $name,
You are version $version.
Keep being awesome!''';
print(message);
// Number arithmetic
int apples = 10;
int friends = 3;
print('Each gets: ${apples ~/ friends} apples'); // 3
print('Leftover: ${apples % friends}'); // 1
// Double for precision
double price = 29.99;
double tax = 0.08;
double total = price + (price * tax);
print('Total: $${total.toStringAsFixed(2)}'); // $32.39
// Parsing strings to numbers
var input = '42';
var number = int.parse(input);
print('Double it: ${number * 2}'); // 84
// Random numbers
var rng = Random();
var dice = rng.nextInt(6) + 1; // 1-6
print('You rolled a $dice!');
}Line-by-line walkthrough
- 1. Importing the dart:math library for math functions
- 2.
- 3. The main function starts
- 4. A comment for string interpolation section
- 5. Creating a String variable 'name' set to 'Flutter'
- 6. Creating an int variable 'version' set to 3
- 7. Printing a message with both variables embedded using $ syntax
- 8. Using ${} with an expression to print the name's length
- 9.
- 10. A comment for string methods
- 11. An email string with mixed case for demonstration
- 12. toLowerCase() converts the entire string to lowercase
- 13. contains() checks if '@' exists in the string -- returns true
- 14. split('@') breaks the string into a list at the @ symbol
- 15.
- 16. A comment for multiline strings
- 17. Triple quotes begin a multiline string
- 18. The $name variable is interpolated inside the multiline string
- 19. The $version variable is also embedded
- 20. The closing triple quotes end the multiline string
- 21. Printing the multiline message
- 22.
- 23. A comment for number arithmetic
- 24. Declaring apples as int 10
- 25. Declaring friends as int 3
- 26. Integer division ~/ gives 3 (10 divided by 3, no decimal)
- 27. The % modulo operator gives remainder 1 (10 mod 3)
- 28.
- 29. A comment for doubles
- 30. A price as a double
- 31. A tax rate as a double
- 32. Calculating total by adding price plus price times tax
- 33. Printing the total formatted to 2 decimal places with a dollar sign
- 34.
- 35. A comment for parsing
- 36. A string variable that looks like a number
- 37. int.parse() converts the string '42' to the integer 42
- 38. Multiplying the parsed number by 2 and printing the result
- 39.
- 40. A comment for random numbers
- 41. Creating a Random number generator
- 42. Generating a random integer from 1 to 6 (like a dice roll)
- 43. Printing the dice result
Spot the bug
void main() {
var price = '19.99';
var quantity = 3;
var total = price * quantity;
print('Total: $total');
}Need a hint?
Look at the types. Can you multiply a String by an int?
Show answer
price is a String ('19.99'), not a double. You cannot multiply a String by an int. Fix: change to var price = 19.99; (without quotes) or use double.parse('19.99') * quantity.
Explain like I'm 5
Strings are like making friendship bracelets with letter beads. You can put them together ('Hello' + 'World'), find a bead ('Where is the @?'), change all beads to big letters (UPPERCASE), or cut the bracelet and rearrange pieces. Numbers are like your calculator in school -- addition, subtraction, multiplication, division. The $ sign in strings is like a magic window -- when Dart sees $name, it peeks at the jar labeled 'name' and puts whatever is inside right into the sentence!
Fun fact
Dart uses UTF-16 encoding for strings, which means it can handle characters from every human language, including Chinese, Arabic, emoji, and ancient Egyptian hieroglyphics. The string 'Hello' takes 10 bytes in memory (2 bytes per character in UTF-16).
Hands-on challenge
Write a program that calculates the area of a circle. Ask for the radius (use a variable), compute area = pi * r * r, and print the result formatted to 2 decimal places using toStringAsFixed(2). Bonus: Also calculate the circumference!
More resources
- Dart Strings (Dart Official)
- Dart Numbers (Dart Official)
- dart:math Library (Dart API)