Variables are the building blocks to know when you learn a new programming language. In today's article we are going to talk about variables in Dart.
Dart has built-in types like other programming language:
- int for integers
- double for floating numbers
- boolean for boolean value
- String for text
To declare a variable in Dart, we define the variable type followed by the variable name
int currentYear = 2023; double pi = 3.14; bool isAdult = true; String name = "Lionel Messi"
Type inference: var & dynamic
Although, you are not forced to specify the variable type thanks to a mechanism called "type inference". It means that Dart can infer (or simply guess) the type of the variable
var myAge = 27; var country = "Madagascar"
In the example above, Dart will assume that the variable myAge is an integer and the variable country is a string due to the presence of the double quotes. When declared with the var keyword, the type of the variable can't be changed throughout the execution of the program.
The dynamic keyword can also be used to declare a variable. The difference with var is that the type of the variable can change during the execution of the code.
dynamic myVar = "Hello" print(myVar.runtimeType) // String myVar = 123 print(myVar.runtimeType) // int
The important thing to remember is:
- var can't change the TYPE of the variable, but can change the VALUE of the variable later in code
- dynamic can change the TYPE of the variable and can change the VALUE of the variable later in code
- final can’t change TYPE of the variable, and can’t change VALUE of the variable later in code.
var myVar = "Hello" dynamic myDynamicVar = "Hello" myVar = 123 // not possible myDynamicVar = 123 // possible
Note: If you state a var without intializing, it becomes a dynamic
var myVar; myVar = "abc"; print(myVar.runtimeType) // String myVar = 1245; print(myVar) //1245 print(myVar.runtimeType) // int
That's all for today's article. If you want to deep dive into the fundamentals of Dart, check out the official documentation.
Top comments (0)