Explain it simply
Explain it simply
A data type is a label that tells Dart what kind of thing a value is, and therefore what you are allowed to do with it. Picture labelled jars in a kitchen: nobody expects to pour soup into the jar marked sugar. Dart puts such a label on every value. Whole numbers are int, numbers with a decimal point are double, text is String, and yes/no answers are bool.
The labels are checked before your program runs. If you try to put the text '20' into a variable meant for whole numbers, Dart refuses to compile the file and points at the offending line, so the mistake never reaches a user.
Problem → Why → Solution
The problem: everything from a form arrives as text
A signup form hands your program everything as text, even the age field. The three lines below look natural to someone arriving from another language, and Dart rejects every one of them. The first puts text into an int variable, the second adds a number to text, and the third assigns the result of 7 / 2 to an int. That last one surprises people, because many languages quietly cut off the decimals when you divide two whole numbers.
void main() {
// Everything typed into a form arrives as text.
String ageText = '20';
int age = ageText; // error: String is not an int
int nextYear = ageText + 1; // error: cannot add an int to a String
int half = 7 / 2; // error: / produces a double
}Why does Dart refuse instead of guessing?
Dart checks types before the program starts, so an impossible assignment becomes a compile-time error with a line number instead of a strange value in production. In JavaScript the expression '20' + 1 quietly turns into the text '201'; Dart stops you and makes you decide whether you meant parsing or joining. The price is that you convert explicitly, with int.parse or int.tryParse. That is a good trade, because the conversion is exactly where bad user input shows up.
Core concept: how Dart's type system works
Dart is a statically typed language with sound null safety. The analyzer knows the type of every expression before the program runs, and a variable of type int can never hold anything else. You can write var or final and let Dart infer the type: after var count = 3; the variable is an int for good. That is type inference, not looser checking.
There are two number types. int is a whole number; on the Dart VM (the dart command, and Flutter on a phone) it is a 64-bit signed integer, so it covers -9223372036854775808 to 9223372036854775807, and arithmetic past either end wraps around. When Dart is compiled to JavaScript for the web, numbers are JavaScript numbers and an int is only exact up to 2^53, so do not rely on huge integers in code that ships to browsers. double is a 64-bit IEEE 754 floating-point number, which is why 0.1 + 0.2 prints 0.30000000000000004. num is the common parent of both, handy when a function accepts either one.
The / operator always returns a double, even when both sides are ints and divide evenly: 6 / 2 is 3.0. For whole-number division use ~/, which truncates, and use % for the remainder. An int literal may initialise a double variable (double price = 3; stores 3.0), but a double can never go into an int.
A String is an immutable sequence of UTF-16 code units. Single and double quotes are interchangeable, and $name or ${expression} inserts values into the text. length counts UTF-16 code units, so a single emoji can report 2. Methods such as toUpperCase never change the original; they return a new string. A bool is exactly true or false: Dart does not treat 0, '' or null as false, so if (count) does not compile when count is an int.
Conversion is always explicit. int.parse('42') returns 42 but throws a FormatException for bad text, so for user input prefer int.tryParse, which returns an int? and gives null when the text is not a number. A ? after a type means nullable: once you hold an int? you must handle the null, with ??, an if check or ?., before using it as an int. dynamic switches type checking off, so keep it for the rare case where the type genuinely cannot be known.
- Every value carries a type label
- The analyzer checks each use of it
- A mismatch is a compile error
- Convert yourself: parse or tryParse
Types catch mistakes before the program starts, but whether a user's text really is a number is only known at run time, so you check it with tryParse.
General pattern
int whole = 0;
double fraction = 0.0;
num either = 0;
String text = '';
bool flag = false;
int? maybeWhole; // nullable, starts as null
var inferred = 'type comes from the first value';
int converted = int.parse(text);
int? safe = int.tryParse(text);The type name comes before the variable name. A ? after the type allows null, and var asks Dart to infer the type from the first value. To turn text into a number you have int.parse, which throws on bad text, and int.tryParse, which returns null instead.
Example: four basic types and a conversion
This example declares one value of each basic type and prints it. Then it divides two whole numbers to show the difference between / and ~/, and converts the text '42' with int.parse and the text '4x2' with int.tryParse. Watch the second conversion come back as null.
void main() {
int students = 35;
double rating = 4.8;
String course = 'Dart Basic';
bool isPublished = true;
print(course.runtimeType);
print('Students: $students');
print('Rating: $rating');
print('Published: $isPublished');
// / always produces a double, ~/ keeps only the whole part
print(students / 2);
print(students ~/ 2);
// text coming from outside must be converted explicitly
String input = '42';
int parsed = int.parse(input);
int? bad = int.tryParse('4x2');
print(parsed + 1);
print(bad);
}Code breakdown
- Line 2
int students = 35;This declares a variable of type int. Writing 35.5 here would put a double into an int and fail to compile.
- Line 7
print(course.runtimeType);runtimeType reports the value's actual type, here String. It is useful when debugging, but in normal logic an is check is the better tool.
- Line 13
print(students / 2);Both 35 and 2 are ints, yet / returns a double, so the output is 17.5.
- Line 14
print(students ~/ 2);~/ is whole-number division: it drops the fraction and returns the int 17.
- Line 18
int parsed = int.parse(input);This turns the text '42' into the int 42. If input were 'abc', this line would throw a FormatException.
- Line 19
int? bad = int.tryParse('4x2');tryParse returns null instead of throwing when the text cannot be converted, which is why the variable type is int?. print(bad) shows null.
String
Students: 35
Rating: 4.8
Published: true
17.5
17
43
nullint, double and num side by side
| Type | What it holds | Example |
|---|---|---|
| int | Whole numbers (64-bit on the VM) | 42, -7, 0 |
| double | Decimal numbers (64-bit floating point) | 4.8, -0.5, 3.0 |
| num | Either an int or a double | 5, then later 2.5 |
A num variable can start as an int and later hold a double, but while it is typed num you cannot call int-only methods on it directly. When you know which kind of number you need, write int or double precisely. The code below shows what happens when numbers mix, how % treats a negative left side, and why comparing doubles with == cannot be trusted.
void main() {
num total = 10; // holds an int for now
total = total + 2.5; // now it holds a double
print(total);
double price = 3; // an int literal is fine for a double
print(price);
print(7 % 3); // remainder: 1
print(-7 % 3); // 2: with a positive divisor % is never negative
print((7 / 2).round()); // 3.5 rounds to 4
print(7.9.toInt()); // 7: toInt cuts off the fraction
print(0.1 + 0.2 == 0.3); // false: binary floating-point rounding
}Turning text into numbers safely
Text typed by users can contain spaces, letters and negative signs, so it is safest to gather the parsing into one function that returns an int?. A caller cannot use that result as a plain int without dealing with null, so the compiler helps you not to forget. The code also shows the is operator at the bottom: after if (value is String) checks an Object variable, you can use value as a String inside that block, which Dart calls type promotion.
int? readAge(String text) {
int? age = int.tryParse(text.trim());
if (age == null || age < 0) {
return null;
}
return age;
}
void main() {
print(readAge('29'));
print(readAge('abc'));
print(readAge('-4'));
print(readAge(' 18 '));
Object value = 'Dart';
if (value is String) {
print(value.toUpperCase()); // value is promoted to String here
}
}var, dynamic and Object are different things
After var x = 'hi'; the variable x is fixed as a String and x = 5; is a compile error. dynamic y = 'hi'; accepts y = 5; and defers checks such as y.length until run time. Object z = 'hi'; accepts any value, but you may only call methods that Object itself has, so to use String methods you first test with is.
In real projects
Where this shows up in real projects
In a Flutter app, the value a TextField gives you is a String. Reading a quantity, a price or an age usually means converting with tryParse and showing an error message when the result is null. When JSON arrives from a server, jsonDecode reads 5 as an int and 5.5 as a double. If an API sometimes sends 5 instead of 5.0, data['price'] as double crashes with "type 'int' is not a subtype of type 'double' in type cast"; the fix is (data['price'] as num).toDouble().
Type choice also matters for money. If you store a running total of kyat in a double, rounding errors like 0.1 + 0.2 pile up and the books stop matching, so real systems keep the smallest unit (pyas, or cents) in an int and only add the decimal point when displaying it. And if your code also compiles for the web, store very large identifiers as a String rather than an int.
Common mistakes
Common mistakes
1. Calling int.parse directly on user input
int.parse('abc') throws FormatException: Invalid radix-10 number and, if nobody catches it, ends the program. That is acceptable for data you control, but for anything a user types or a file contains, use int.tryParse and check for null.
2. Expecting / to return an int
Compiling int half = a / 2; gives "A value of type 'double' can't be assigned to a variable of type 'int'." If you want a whole-number answer use a ~/ 2, and if you want a fraction store it in a double. (a / 2).toInt() also works, but ~/ is shorter and states the intent better.
3. Reaching for dynamic to silence an error
Making a variable dynamic to get rid of a compiler error removes the error message, but the mistake moves to run time and appears in front of a user. Fix the cause, for example using an int? as if it were an int, instead of removing the type.
4. Comparing doubles with ==
0.1 + 0.2 == 0.3 is false, because decimal fractions are stored in binary and end up slightly off. Keep exact values such as prices in an int, or compare within a tolerance like (a - b).abs() < 0.0001.
Best practices
Best practices
- Convert outside text with int.tryParse or double.tryParse and handle the null right away.
- Write int or double instead of num whenever you know which kind of number you mean.
- Do not store money in a double; keep the smallest unit in an int.
- You do not need to spell out every type: use var or final for local variables, and write types on public APIs.
Mini challenge
Mini challenge: validating an order quantity
Read the quantity an order form sends safely, then do a small page-count calculation for the shop.
- int? parseQuantity(String text): trim the text, and return null if it is not a whole number or is less than 1
- double average(int a, int b): return the mean of a and b as a double
- int pages(int items, int perPage): round up using only int arithmetic (25 items at 10 per page gives 3)
- In main, check '12', 'twelve' and '0' with parseQuantity, then print average(7, 8) and pages(25, 10)
int? parseQuantity(String text) {
// TODO: tryParse the trimmed text, then reject anything below 1
}
double average(int a, int b) {
// TODO: remember what / returns
}
int pages(int items, int perPage) {
// TODO: round up without using double
}
void main() {
// TODO: print parseQuantity for '12', 'twelve' and '0'
// TODO: print average(7, 8) and pages(25, 10)
}Expected: 12 null null 7.5 3
Show hint
To round up an integer division, think of the shape (items + perPage - 1) ~/ perPage. In parseQuantity the tryParse result can be null, so check for null before you compare it.
Show solution
int? parseQuantity(String text) {
final value = int.tryParse(text.trim());
if (value == null || value < 1) {
return null;
}
return value;
}
double average(int a, int b) {
return (a + b) / 2;
}
int pages(int items, int perPage) {
return (items + perPage - 1) ~/ perPage;
}
void main() {
print(parseQuantity('12'));
print(parseQuantity('twelve'));
print(parseQuantity('0'));
print(average(7, 8));
print(pages(25, 10));
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Dart is statically typed, so assignments with the wrong type are caught as compile errors before the program runs.
- / always returns a double, ~/ returns the whole part and % returns the remainder; int is 64-bit on the VM but only exact up to 2^53 on the web.
- Convert outside text with int.tryParse and handle the null in the resulting int? before using it.
- var infers a type while dynamic turns type checking off; they are not the same thing.
Dart language overview — Dart