Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Dart notes · Topic 2 of 19 · 6 min read

Dart variables, data types and constants

Dart variables notes with examples: int, double, String, bool, var, final and const, type conversion with parse and toString, and string interpolation.

What is a variable?

A variable is a named box that holds a value. You give it a name, put a value in, and use the name later instead of the value.

void main() {
  String name = 'Asha';
  int age = 15;
  print(name);
  print(age);
}
Asha
15

String name = 'Asha'; has three parts: the type (String), the name (name) and the value ('Asha').

Naming rules

  • Names may use letters, digits, _ and $, but must not start with a digit.
  • Names are case-sensitive: marks and Marks are different variables.
  • Keywords such as class, if and var cannot be names.
  • Dart style is lowerCamelCase: totalMarks, studentName, isPassed.
  • Choose names that say what the value means: feePerMonth, not x.

The basic types

TypeHoldsExample
intwhole numbersint roll = 21;
doubledecimal numbersdouble price = 99.50;
numeither an int or a doublenum total = 10;
StringtextString city = 'Ranchi';
booltrue or falsebool isPassed = true;

Every value in Dart is an object, even numbers, so they have properties and methods:

void main() {
  int marks = 87;
  double height = 5.75;
  print(marks.isEven);
  print(height.round());
  print(marks.runtimeType);
}
false
6
int

var: let Dart work out the type

With var, Dart infers the type from the first value. The type is then fixed.

void main() {
  var city = 'Ranchi';   // Dart infers String
  var pin = 834001;      // Dart infers int
  city = 'Dhanbad';      // fine: still a String
  print('$city $pin');
}
Dhanbad 834001

Assigning a different type later is an error: after var pin = 834001;, the line pin = 'none'; fails with *A value of type 'String' can't be assigned to a variable of type 'int'.*

dynamic switches type checking off for a variable. Avoid it in normal code; it hides mistakes until the program runs.

Changing values

A normal variable can be given a new value at any time:

void main() {
  int score = 10;
  score = score + 5;
  score += 5;
  print(score);
}
20

final and const: values that never change

KeywordSet whenUse it for
finalonce, when the program runsa value worked out at run time, such as today's date
constat compile time, before the program runsfixed values written in the code, such as a tax rate
void main() {
  const gstRate = 18;               // known before the program runs
  final today = DateTime.now();     // known only when it runs
  final total = 1000 + 1000 * gstRate / 100;
  print(total);
  print(today.year > 2000);
}
1180.0
true

Both refuse a second assignment: gstRate = 12; is an error. Prefer final for any variable you never reassign; it makes code easier to trust. Dart style writes constants in lowerCamelCase too (gstRate, not GST_RATE).

Converting between types

void main() {
  int a = int.parse('42');          // String to int
  double b = double.parse('3.5');   // String to double
  String c = 42.toString();         // int to String
  int d = 9.99.toInt();             // double to int: cuts off the decimals
  double e = 7.toDouble();          // int to double
  String f = 3.14159.toStringAsFixed(2);
  print('$a $b $c $d $e $f');
}
42 3.5 42 9 7.0 3.14

int.parse('abc') throws a FormatException. When the text may not be a number, use int.tryParse, which returns null instead:

void main() {
  print(int.tryParse('25'));
  print(int.tryParse('25 kg'));
}
25
null

Building sentences with $ and ${ }

$name puts a variable's value into a string. ${ } puts in the value of any expression:

void main() {
  String name = 'Rohit';
  int maths = 78, science = 84;
  print('$name scored ${maths + science} out of 200.');
  print('Name has ${name.length} letters.');
}
Rohit scored 162 out of 200.
Name has 5 letters.

Use ${ } whenever there is more than a bare variable name, for example a sum, a method call or a property.

Example: a simple interest calculator

void main() {
  const principal = 50000;
  const rate = 8.5;
  const years = 3;
  final interest = principal * rate * years / 100;
  print('Interest: Rs ${interest.toStringAsFixed(2)}');
  print('Amount  : Rs ${(principal + interest).toStringAsFixed(2)}');
}
Interest: Rs 12750.00
Amount  : Rs 62750.00

Common mistakes

  • Writing int price = 99.5;. An int cannot hold a decimal; use double.
  • Reassigning a final or const variable.
  • Using const for a value known only at run time, such as const now = DateTime.now();.
  • Forgetting braces: '$a+b' prints the value of a followed by +b; write '${a + b}'.
  • Using int.parse on text a user typed without handling bad input; prefer int.tryParse.

Key points

  • A variable has a type, a name and a value.
  • The basic types are int, double, num, String and bool.
  • var infers the type once; it cannot change afterwards.
  • final is set once at run time; const is fixed at compile time.
  • Convert with int.parse, double.parse, toString, toInt, toDouble and toStringAsFixed.
  • $name and ${expression} insert values into strings.

Practice questions

1. Store a student's name, roll number, percentage and pass status in four variables of the right types and print them in one sentence.
void main() {
  String name = 'Meena';
  int roll = 12;
  double percent = 82.5;
  bool passed = true;
  print('$name (roll $roll) scored $percent% - passed: $passed');
}
2. What is the difference between final and const?

Both can be assigned only once. A const value must be known at compile time (written in the code); a final value can be worked out while the program runs, such as DateTime.now().

3. What does this print? var x = 7.9; print(x.toInt());

7. toInt() cuts off the decimal part; it does not round.

4. Write a program that converts 37 degrees Celsius to Fahrenheit (F = C x 9 / 5 + 32) and prints the answer with one decimal place.
void main() {
  const c = 37;
  final f = c * 9 / 5 + 32;
  print('${f.toStringAsFixed(1)} F');   // 98.6 F
}
5. Why is var count = 5; count = 'five'; an error?

var infers the type int from the first value, and the type is then fixed, so a String cannot be assigned to it.