Variables in Dart
Overview
Each and every programming language deals with variables. So, this article is all about variables in Dart, their types, usage, and declaration in Dart. A Dart variable is a piece of memory that can contain a data value or it is "a named space in the memory" that is used to store and manipulate the value or data. There are various types of variables present in Dart, and we need to follow some rules for writing a variable.
Introduction
A Dart variable is a piece of memory that stores a value, and that value or data can be manipulated. Variables are typically used to store information that your Dart programme needs to do its job.
We need to follow some rules for writing a variable-
- Variables are case sensitive means var name is not same as var NAME.
- Keywords can not be used as variables
- Variables cannot contain white spaces or special characters except the underscore (_) and the dollar ($) sign.
- First character should be an alphabet and not a number.
- Variable names should be related to the code.
Declaring Variables
var keyword
In Dart, variables are declared using var keyword followed by a variable name. A variable declared by var keyword can hold any kind of value like String, int, double etc. The value of a var variable can not change within the program once it is initialized at declaration.
Type annotations for explicit typing
Type annotation means what kind of data is stored in this variable like String, number, boolean etc. Type annotations provide clarity to the code so that Dart compiler infer the exact type. In type annotation, we declare a data type as its prefix before the variable name. Syntax is like shown below.
Final and const keywords for constants
Both final and const are of similar type and used when you do not want to re-assign the value. But ofcourse, they are not same but are different.
final
- A variable with the final keyword will be initialized at runtime and can only be assigned for a single time.
- In a class and function, you can define a final variable.
const
- A variable with the const keyword is initialized at compile-time and is already assigned when at runtime.
- We can’t define const inside a class. But you can define in a function.
Data Types in Dart
The Dart data type defines, what kind of data is stored in this variable. Each variable has its data type. The Dart is a static type of language, which means that the variables can not modify.
A. Numbers
In Dart Numbers, we store numeric values which can be an integer or a double value.
- int represents an integer value or a whole number like 20, 40,100.
- double represents the floating-point values or decimal numbers like 1.0, 2.5, 5.5
B. Strings
Strings represent sequences of characters that are signified by using either single quotes or double quotes. We can store data like name, hobby, address, etc.
C. Booleans
Boolean represents two values and they are true or false. The keyword used for Boolean type is bool and we use it when we want to show some data based on true, or false conditions.
D. Lists
Dart Lists are similar to array and Lists contains a collection of the ordered objects or values. Lists in Dart can hold elements of any type, including other lists. We represent a list with [] brackets and values separated by a comma(,).
E. Maps
Maps in Dart represent a collection of key-value pairs. The keys and values can be of any type. It is important to know that, keys must be unique in maps while values can repeat.
F. Runes and Symbols
Dart Runeisre is a special string of Unicode UTF-32 units. It is used to represent the special syntax. Different special characters are equal to different Unicode codes.
Variable Initialization
1. Initializing variables at declaration
Initializing variables at declaration means assigning an initial value to a variable when you declare it. We generally declare some value or data to the variable from the start.
2. Lazy initialization with 'late' keyword
In Dart, the late keyword is used for lazy initialization of non-nullable variables. It means, we declare a variable without giving a value to it but guarantee that it will be assigned a value before it is accessed for the first time.
3. Default values for uninitialized variables
The default value for all types in Dart is null if nothing else is specified when declaring the variable. Remember that numeric type variables are initially assigned with the null value.
Scope and Lifetime of Variables
1. Global variables
We can define a global variable by declaring it outside of any classes, methods, or functions. Global variables are accessible from any part of the code within the same file.
2. Local variables
In Dart, local variables are variables that are declared within the scope of a function, method, or block of code. They are accessible only within the block of code and not outside the block. It has advantages like isolation and effective memory management.
3. Block-level scope
Block-level scope refers to the visibility or accessibility of variables declared within a block of code, such as within a function, loop, or conditional statement.
4. Garbage collection and memory management
Dart is a garbage-collected language, that handles memory management automatically, relieving developers from manually managing memory allocation and deallocation.
Garbage Collection - It is a process where the Dart runtime system automatically identifies and reclaims the memory that is no longer in use. It frees up memory occupied by objects that are no longer needed.
Memory Management - Dart automatically allocates memory for those objects on the heap.
Type Inference
Type inference in Dart is a feature that allows the Dart compiler to automatically gets the data type of a variable based on its assigned value.
This inference happens during compile-time, and the compiler ensures that the inferred types are consistent throughout the variable's scope.
Dynamic vs. Static Typing in Dart
In statically-typed languages like Dart, the data type of a variable is explicitly declared at compile-time, and it remains fixed throughout the variable's lifetime.
In dynamically-typed languages, Javascript, and Dart(when using dynamic type), their types are determined at runtime based on the value assigned to them.
Type Conversion and Casting
1. Implicit type conversion
Implicit conversion means the automatic conversion of a value from one data type to another by the Dart runtime system.
2. Explicit type casting
Explicit casting means manually converting a value from one data type to another, the developer has to indicate the desired data type explicitly.
Null Safety with Variables
Null safety means that a variable cannot have a null or void value unless specified. In Dart, there are two types of null safety annotations for variables-
- Non-Nullable Variables - We must provide an initial value when declaring a non-nullable variable.
- Nullable Variables - These can hold null values, either by appending ? or late keyword.
Conclusion
We have learned about variables in Dart in detail. Here are the key points:
- Variables are used to store a value or data in Dart.
- We have discussed variable declaration, scopes, type inference, and null safety in detail.
- Always try to specify the type of variable, like String, bool, int, etc., before a variable name.
- For good memory management practice, try to use a local variable whenever possible.
- We should use const or final if values are not re-assigned.