Variables Fundamentals of variables and common data types in Dart

This lesson is available for PRO members or as a single course purchase. Sign-in and choose a plan below.
Get Unlimited PRO Access

OR


*Enrollment provides full access to this course (and updates) for life.

Basic data types

Declare a variable by putting the data type in front of the variable name.

file_type_dartlang main.dart
int num1 = 2;
double num2 = 3.0;
bool isTrue = true;
String str = 'Hello';

Runtime Type Checking

You can check the runtime type of a variable using the is keyword, or via its runtimeType property.

file_type_dartlang main.dart
(num1 + num2) is int
(num1 + num2).runtimeType

Var Keyword

The var keyword is like saying I don’t care to annotate the variable with a type. If you don’t specify a value, it will be automatically inferred as dynamic (try to avoid this).

file_type_dartlang main.dart
var username; // dynamic
var username = 'fireship'; // String

Final vs Const

The final keyword is used to declare a variable that cannot be reassigned. It’s a good practice to use final whenever possible.

file_type_dartlang main.dart
final String fullname = 'Jeffrey';
fullname = 'Jefferson' // error;

The const keys is almost identical to final, but it creates an immutable compile-time constant. It may improve app performance, but can only be used for values known at compile time.

file_type_dartlang main.dart
const int age = 75;
const int favNumber = num1 + 5; // error

See more in the official docs

Q&A Chat