Dart Programming 101: Mastering Variables for Efficient Coding

In this article, Dart Programming 101: Mastering Variables for Efficient Coding, we will explain how variables in the Dart programming language should be properly implemented, and discuss the different types of variables in Dart.

Introduction

Mastering Variables for Efficient Coding

At its simplest, computer programming is all about manipulating data, since everything you see on your screen can be reduced to numbers. Sometimes you represent and work with data as various types of numbers, but other times, the data comes in more complex forms such as text, images
and collections.
In your Dart code, you can give each piece of data a name you can use to refer to that piece of data later. The name carries with it an associated type that denotes what sort of data the name refers to, such as text, numbers, or a date.

Variables as Storage Locations

Variables are essentially named storage locations that hold data, and they serve as a way to store values in memory that your program can work with. The type of data that a variable can hold is determined by its data type, such as int, double, String, etc. Dart is a statically-typed language, meaning that the type of a variable is determined at compile-time.

Different Kinds of Variables

Dart has two different types of “variables” whose values never change. They are declared with the const and final keywords, and the following sections will show the
difference between the two.
In dart you can declare variables using final, const, or var.

Mastering Variables for Efficient Coding

final variable

If I explain final variables in one line: final means that the variable can only be set once (though you can set it later).

A final variable can be assigned when the program runs (at run-time), especially if the value depends on something that is only known when the program is executed, like user input, or a value fetched from an API or database, once the final variable is assigned during run-time, it cannot be changed again.

However, if this is unclear, let me explain further. To understand final and const, it’s important to first discuss the concepts of Compile-Time and Run-Time, and why we encounter errors at both stages, like compile-time errors and run-time errors.

Mastering Variables for Efficient Coding

Compile-Time Run

Compile-Time refers to the process when your code is translated from a high-level programming language to machine code (or bytecode, depending on the language) by the compiler.

Errors detected during this phase are called compile-time errors. These errors include syntax errors, type mismatches, or missing semicolons. They occur when you compile the code.

The goal of compile-time checking is to ensure the code is syntactically correct and follows the rules of the programming language.

Run-Time

Run-time errors occur while a program is executing, even after it has successfully passed through compile-time checks. These errors cannot be detected during the compilation phase because they arise due to conditions that only occur when the program is running.

Examples of run-time errors include:

Unhandled promise rejection (common in asynchronous programming, such as JavaScript): If a promise fails to resolve or rejects unexpectedly, and this condition is not handled properly in the code, it will result in a run-time error. The failure is only evident when the promise is executed.

Division by zero: If you attempt to divide a number by zero, the error will only be triggered when the program tries to perform that specific operation during execution.

Null pointer exception: This occurs when your program tries to access or modify an object or variable that hasn’t been initialized or is pointing to null. The error happens at run-time because the issue only arises when the program tries to use the uninitialized object.

Array index out of bounds: If your program attempts to access an index that is outside the valid range of an array, it will cause an error at run-time, since the array’s size is only checked during execution.

File not found: When your program tries to open a file that doesn’t exist, this error will be thrown during execution because the presence of the file can only be verified at run-time.

const constants

Variables whose value you can change are known as mutable data. Mutable certainly have their place in programs, but can also present problems. It’s easy to lose track of all the
places in your code that can change the value of a particular variable. For that reason, you should use constants rather than variables whenever possible. These unchangeable
variables are known as immutable data.

const means the value is constant and is set at compile-time.

To create a constant in Dart, use the const keyword:

Mastering Variables for Efficient Coding

Just as with var, Dart uses type inference to determine that myConstant is an int.
Once you’ve declared a constant, you can’t change its data.

late keyword in Dart

late means the variable’s value can be assigned later in the program, but you promise it will be assigned before it’s used.

Sometimes you want to use a non-nullable type variable, but you can’t initialize it in any of the ways you learned above.

Using late means that Dart doesn’t initialize the variable right away. It only initializes it when you access it the first time. This is also known as lazy initialization. It’s like
procrastination for variables.
It’s also common to use late to initialize a field variable in the constructor body.

Dangers of being late

Mastering Variables for Efficient Coding

Take a look at the following example:

Dart doesn’t complain at you, because using late means that you’re promising Dart that you’ll initialize the field before it’s ever used. This moves checking from compile-
time to runtime.
Now add the following code to main and run it:

Mastering Variables for Efficient Coding

You broke your word and never initialized name before you used it. Dart is disappointed with you, and complains accordingly:

LateInitializationError: Field 'name' has not been initialized.

For this reason, it’s somewhat dangerous to use late when you’re not initializing it either in the constructor body or in the same line that you declare it.

It is grammatically impossible to declare a const variable with the late modifier. This is because const variables are set at compile-time, while late variables are meant to be set later during runtime.

Dart has flexible variable declaration rules, but there are strict differences between how final, const, and late variables work. Final and const variables are not meant to change once they’re set, but only const variables are required to be known at compile-time. Instance variables in classes cannot be constant.

Thank you for taking the time to read! Feel free to explore more of our content or leave a comment below.

Learn more about Flutter

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *