Beginner · Dart basics · topic 2 of 50 · 30 min
Your first Dart program, variables and types
Explanation
DartPad: no installation needed
Open dartpad.dev in your browser. It runs Dart (and even small Flutter apps) online. Type code on the left, press Run, and see the output on the right. It is perfect for learning the language before installing Flutter.
void main() {
print('Namaste, Dart!');
}Variables
A variable is a named place to keep a value. Dart gives you four common ways to declare one:
void main() {
var city = 'Kochi'; // type inferred as String; can be reassigned
int seats = 72; // explicit type
final orderTime = DateTime.now(); // set once, value known at run time
const gstPercent = 18; // compile-time constant
city = 'Kozhikode'; // fine
// gstPercent = 12; // error: constant variables can't be assigned
print('$city $seats $gstPercent');
}| Keyword | Can change? | When is the value known? |
|---|---|---|
| var / a type name | Yes | Any time |
| final | No (set once) | When the program runs (for example DateTime.now()) |
| const | No | When the code is compiled (literal values) |
Flutter uses const a lot: const widgets are created once and reused, which saves work. You will see const Text('Hello') everywhere.
Basic types
| Type | Holds | Example |
|---|---|---|
| int | Whole numbers | 72, -5 |
| double | Decimal numbers | 99.5 |
| num | Either int or double | num x = 5; x = 5.5; |
| String | Text in single or double quotes | 'Pune' |
| bool | true or false | true |
| dynamic | Anything; type checks are turned off | Avoid in normal code |
Dart is type safe: once a variable has a type, it keeps it. var city = 'Kochi' makes city a String forever, so city = 5 is a compile error. The analyser in your editor shows such mistakes as red underlines before you even run the program, which saves a lot of debugging time.
Numbers and division
void main() {
print(10 / 4); // 2.5 (/ always gives a double)
print(10 ~/ 4); // 2 (~/ is integer division)
print(10 % 4); // 2 (remainder)
print(10 / 2); // 5.0 (still a double)
}String interpolation
void main() {
final item = 'Vada pav';
final price = 25;
final qty = 4;
print('$item x $qty = Rs ${price * qty}'); // Vada pav x 4 = Rs 100
print('Name length: ${item.length}'); // Name length: 8
const address = '''
Shop 12, Market Road
Pune 411001'''; // multi-line string
print(address);
}Converting text to numbers
void main() {
print(int.parse('42') + 1); // 43
print(int.tryParse('4two')); // null instead of an exception
print(double.tryParse('99.5')); // 99.5
print(42.toString().length); // 2
}Common mistakes
- Expecting 7 / 2 to be 3. In Dart, / gives 3.5; use 7 ~/ 2 for 3.
- Using dynamic to avoid type errors. You lose the compiler's help.
- Forgetting semicolons at the end of statements.
- Using const for values only known at run time, like DateTime.now(): a compile error. Use final.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Your first Dart program, variables and types · 1/7
void main() {
print('Namaste, Dart!');
}Every Dart program starts in void main. print shows a line.
Prefer a video by a teacher? Find free videos on “dart programming basics variables final const types dartpad” on YouTube ↗
In real life: A simple restaurant bill
A restaurant owner wants a quick bill calculation: dish prices are fixed (const), quantities come from the order, and GST is added at the end. String interpolation prints a clean line for the customer.
void main() {
const dosaPrice = 90;
const coffeePrice = 40;
final dosas = 2;
final coffees = 3;
final subtotal = dosaPrice * dosas + coffeePrice * coffees;
final gst = subtotal * 5 / 100;
print('Subtotal Rs $subtotal, GST Rs ${gst.toStringAsFixed(2)}, Total Rs ${(subtotal + gst).toStringAsFixed(2)}');
}Practice (0/3 done)
What does this print? void main() { final a = 17; print('${a ~/ 5} ${a % 5}'); }
Which declaration does NOT compile?
In DartPad, write a program for a mobile recharge: a const for the plan price (299), a variable wallet balance (500), subtract the plan, and print "Balance after recharge: Rs X" with interpolation. Then convert "149" with int.parse and "abc" with int.tryParse, and print both.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Control flow and collectionsDart basics · same module
- FunctionsDart basics · same module
- First program, val and var, and typesKotlin and Android App Development · Kotlin basics
- Variables, types and constantsC++ Programming (modern C++ and DSA) · First steps: compiling, output, variables and input
- Types and variablesC# and .NET · Getting started with C# and .NET
- Variables, basic types and zero valuesGo Programming (backend and cloud) · Getting started with Go
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
What does 10 / 2 give in Dart?
Answer: 5.0 (a double)
The / operator always returns a double.
Which keyword is for a value fixed at compile time?
Answer: const
const values are known while compiling.
What does int.tryParse('x9') return?
Answer: null
tryParse returns null for invalid text.
Which inserts an expression into a string?
Answer: 'Total: ${a + b}'
${...} evaluates the expression.
Why avoid dynamic?
Answer: It turns off type checking, so mistakes appear only at run time
Static types catch errors early.
How do you put an expression inside a string?Related
Answer: "Total: ${a + b}"
${ } evaluates the expression in a string template.
What is in an int variable declared inside main with int n; and no value?Related
Answer: Garbage: reading it is undefined behaviour
Local variables are not set to zero automatically. Always initialise them.
const int Max = 10; Max = 20; What happens?Related
Answer: Compile error: a const cannot be changed
A const value is fixed at compile time and cannot be assigned again.
From Types and variables
Which type is another name for int32 and holds one Unicode character?Related
Answer: rune
rune is an alias for int32 and represents a Unicode code point.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 2 more topics in “Dart basics” before its exam: Control flow and collections, Functions.
- Module 1 exam: Dart basics · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
- Then the next module, Null safety and object-oriented Dart. 50 topics left in the course before the final exam.