Skip to content

Beginner · Dart basics · topic 2 of 50 · 30 min

Your first Dart program, variables and types

Explanation

Dart programs start in void main(). print shows a line. Declare variables with var (type inferred), an explicit type, final (set once at run time) or const (fixed at compile time). Common types are int, double, num, String and bool. String interpolation puts values into text with $name and ${expression}. Use ~/ for integer division and int.tryParse for safe conversion.

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.

dart
void main() {
  print('Namaste, Dart!');
}
main is where every Dart program starts. void means it returns nothing. Statements end with a semicolon.

Variables

A variable is a named place to keep a value. Dart gives you four common ways to declare one:

dart
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');
}
Prefer final for values that do not change, and const for values known while writing the code.
KeywordCan change?When is the value known?
var / a type nameYesAny time
finalNo (set once)When the program runs (for example DateTime.now())
constNoWhen 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

TypeHoldsExample
intWhole numbers72, -5
doubleDecimal numbers99.5
numEither int or doublenum x = 5; x = 5.5;
StringText in single or double quotes'Pune'
booltrue or falsetrue
dynamicAnything; type checks are turned offAvoid 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

dart
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)
}
On the Dart VM, a double like 5.0 prints with .0; on the web it may print 5. Use ~/ when you want an int.

String interpolation

dart
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);
}
$name inserts a variable; ${...} inserts any expression. Triple quotes make multi-line strings.

Converting text to numbers

dart
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
}
parse throws a FormatException on bad text; tryParse returns null, which is safer for user input.
Think of it like this: final is like the date printed on your train ticket when you book it: it is fixed once printed, but it was decided at booking time. const is like the train number printed in the timetable book: fixed before anyone even opened the ticket counter.

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.

dart
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)}');
}
Prints: Subtotal Rs 300, GST Rs 15.00, Total Rs 315.00

Practice (0/3 done)

Task 1 · Question

What does this print? void main() { final a = 17; print('${a ~/ 5} ${a % 5}'); }

Task 2 · Question

Which declaration does NOT compile?

Task 3 · Practice

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

Question 1

1.What does 10 / 2 give in Dart?

Question 2

2.Which keyword is for a value fixed at compile time?

Question 3

3.What does int.tryParse('x9') return?

Question 4

4.Which inserts an expression into a string?

Question 5

5.Why avoid dynamic?

Read more (free)

Before this, learn

This topic builds on these. If something here feels new, open them first.

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.

From First program, val and var, and types

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.

From Variables, types and constants

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.

From Variables, basic types and zero values

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

  1. 2 more topics in “Dart basics” before its exam: Control flow and collections, Functions.
  2. Module 1 exam: Dart basics · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, Null safety and object-oriented Dart. 50 topics left in the course before the final exam.

← Previous: Flutter and Dart: the big picture