Introduction to Dart Vol. 1: Variables and Data Types

Introduction to Dart Vol. 1: Variables and Data Types

Venturing into the Dart world

In the vast universe of programming, each language has its own structure and style, marking its distinctive identity and usefulness. On this journey towards Dart introduction, we will delve into the fundamental concepts that build the foundations of this modern and powerful language.

Dart, a language developed by Google, has quickly gained popularity thanks to its versatility and efficiency. It is the primary programming language used in Flutter, the open source framework for creating applications for mobile, web, desktop, even embedded systems. Before we dive into creating interactive and dynamic applications, it is essential to understand the most basic building blocks: variables and data types.

Get ready to discover how Dart makes data management an intuitive and powerful experience. Ok, let's begin our journey into the heart of software development with Dart.

Variables

Variables in dart are simply containers of data.

Maybe now is a good time to introduce myself, my name is Lucas. That is information that as human beings we hear frequently or I could tell you that i live in Paraguay or that my ambition is to see all the movies made in history, but if you are a computer, this information is better saved in a variable. The complete line of code looks like this:

var myName = 'Lucas';

var is a keyword that says i'm creating a variable, then i give that variable a name, in this case it's called myName and i set what that variable is equal to in this case it's 'Lucas', and everything else as the point and comma or equal sign are just syntax.

The syntax is just computer grammar, just like we would have commas, periods, colons in English or Spanish language, computers also have their own grammar and this grammar differs fr

om programming language to another but in Dart this is how it looks when you create a new variable.

What is really happening here?

Essentially when i type the var keyword, the computer builds a box, then looks at what name to give that box, in this case it's myName; and then looks at the right side of the equal sign to see what to put inside the box, in this case it's the word 'Lucas' and the semicolon just says that it is the end of this line of code, so the computer can close the box.

Now imagine you have a shelf and as you create more and more variables you will build more shelves full of these boxes, and when you need one you can go, find the box, take it off the shelf and open it to see what's inside.

So, for example if i wanted to print the value of the variable i just created, this is how i would write:

print(myName);

I would use the print function and inside the parentheses i would tell it what i want to print and in this case it is actually not the words myName that will print, it is the value of that variable that will print, so when you run this line of code, the computer will take the box labeled myName from the shelf, open it, see what's inside, and place it on the console. What you will actually see is the Flutter output that says the word 'Lucas'.

For better understanding...

Now so you can try this for yourself and don't have to just rely on what I'm telling you, please go to DartPad, you are going to find something like this:

void main() {
  for (int i = 0; i < 10; i++) {
    print('hello ${i + 1}');
  }
}

Now I want you to delete everything except the void main, you will have something like this:

void main() {
  // Some code...
}

Just so you know, that's a function, and that's the function that acts as the entry point for all of our programs in dart, and now you're telling it to do nothing when it starts, so when you hit run, nothing happens.

We will see what the functions are later.

Inside the main function, declare a variable called myName and initialize it with the String value 'yourName' (if your name is Anya, that's what you'll have to put inside the single quotes). In Dart, Strings are defined using single quotes, although you can also use double quotes if you are coming from other programming languages. However, it is a convention in Dart to prefer single quotes. Finally, be sure to end the line of code with a semicolon.

Once your variable is created, you can use it and to use it, you have to reference the name of the variable, so now write a print function and inside it use the variable that you created and also close that line of code with a semicolon . You should have something like this:

void main() {
  var myName = 'your_name';
  print(myName);
}

Now, click on the run button and you should see your name in the console, which is the value of the variable you created:

your_name

If later you would like to change the name, because you don't like the one you have now, or if you want to change the value that that variable stores, you can simply reassign it.

void main() {
  var myName = 'your_name';

  myName = 'Meryl';
}

And what will happen is that the computer will look for that box that is labeled myName, take its old value inside and put in the new value, so now your name is equal to Meryl.

If you now wanted to print the value of that variable, you would move the print function below the new assignment:

void main() {
  var myName = 'your_name';

  myName = 'Meryl';
  print(myName);
}

What do you think will be printed to the console now? Will it be your old name or will it be Meryl? Press the run button.

Congratulations if you got it right!

In Dart, when you are inside a function, which is delimited by a set of curly braces, the code is executed sequentially, from top to bottom. If you put the print function below the first assignment again, it will print 'your_name', since at that point that is still the assigned value. You then reassign the value to be equal to 'Meryl', and printing it again will display this new value:

void main() {
  var myName = 'your_name';
  print(myName);

  myName = 'Meryl';
  print(myName);
}

Press the run button and you can see it in action.

What if...?

What would happen if you decided to change the value of this variable to something a little different like a number? Let's say you change it to 123.

void main() {
  var myName = 'your_name';
  print(myName);

  myName = 123;
  print(myName);
}

Right now DartPad should be showing you an error like this:

and if you click run everything fails and you have some errors in your console saying this:

compileDDC
main.dart:5:12: Error: A value of type 'int' can't be assigned to a variable of type 'String'.
  myName = 123;
    ^

So, what is an int and why can't it be assigned to a String?

Dart Data Types

We saw that DartPad, when we tried to change the variable that contains a string of characters, basically text and tried to make it contain a number or an integer, was not very happy with that and didn't want to do it. In order to understand what is happening, we have to understand Dart Data Types.

Dart is what we call a statically typed language, what does that mean? Well, let's say we create a variable called myVar, it acts like those children's toys for classifying geometric figures, they have holes with different shapes and you have to fit the correct shape inside the hole. For example, if you had something that was square, it would fit into a square hole, but if you had something circular, it obviously wouldn't fit.

And it's very similar when we have statically typed languages ​​like Dart, essentially when I create a variable and say that variable can only hold pieces of text, then if I try to put a number inside that variable, it won't accept it, it'll say, “I can't mix my types” What are those types we are talking about?

Essentially

They are Data Types, for example we have String, which is a string of characters, like a string of pearls but instead of pearls we have strung some characters. In Dart it is a convention to have single quotes around a piece of text to represent a string, so we know that if we don't have single quotes the computer thinks we're writing code, but if it has single quotes it will know we're trying to specify a string and it doesn't treat it as code.

String myVar = 'Hello';

We also have int which is short for integer and integers are basically all numbers, they can be positive or negative but they cannot have a decimal point.

int myVar = 123;

So if you wanted a decimal point in Dart, you would be working with something called double and this is a data type that allows you to have a decimal point and it will contain your data with all those numbers after the decimal point.

double myVar = 2.7182818284;

The last Data Type we'll look at is something called bool, which is short for boolean and is a data type that can only contain one of two values, true or false.

bool myVar = false;

And all of these data types together are known as Primitive Data Types, so they are the most basic components of any program and we will use them as we develop more and more complex applications to store more and more complex data.

Could it be dynamic?

In Dart, in addition to the primitive data types we also have the dynamic data type. This data type is unique to Dart because it allows flexibility in variable declaration. With dynamic, you can declare a variable without specifying its type and then assign it a value of any type later in the code. This can be useful when you are working with data whose type may change during program execution.

// This is a single line comment in Dart btw <3
dynamic myVar;
myVar = 42; // an Integer
print(myVar); // print 42
myVar = 'Hello World!'; // a String
print(myVar); // print Hello World!

Even if you don't set the type and just use the var keyword, Dart infers that it is of dynamic type.

var myVar; // infers that myVar is dynamic

The benefits of using dynamic include greater flexibility and the ability to work with data more dynamically, adapting to different situations as needed. However, this can also lead to less safe code, since Dart does not perform compile-time type checking for dynamic type variables. This means that errors related to the data type can go unnoticed until the program is running.

Recommendations

In Dart, the type system is quite intelligent and can infer the data type of a variable based on the value assigned to it.

var myVar = 'Hello World!'; // infers that myVar is a String
var myVar = 123; // infers that myVar is an integer

However, if we declare a variable without assigning it an initial value, Dart infers that this variable is of type dynamic. This means that this variable can contain any type of data and Dart will not perform compile-time type checking for this variable.

var myVar; // infers that it is dynamic

It is important to note that while Dart can automatically infer the data type of a variable, it is advisable to specify the type explicitly when declaring variables that will later have a value.

// instead of simply declare:
var myName;
// it's better to do it this way:
String myName;
// don't do this:
var myAge;
// do this:
int myAge;

It is even advisable to use the type even though a value is added to it.

String myName = 'Lucas';
int myAge = 23;

In Dart, in addition to the standard way of declaring variables using var, we also have const and final, which are used for specific purposes and have important differences in their behavior and usage.

  • const: Used to declare **variables whose value is constant at compile time and does not change during program execution.**Const variables are implicitly final, meaning that once they are assigned a value, they cannot be assigned another value later. Additionally, the data type must be explicitly declared.

      const double PI = 3.14159;
    
  • final: Similar to const, final is used to declare variables whose value is constant, but unlike const, the value of a final variable can be assigned at run time. Once a value is assigned, it cannot be changed. The data type must also be explicitly declared.

      final String appName = 'My App';
    

The key differences between const and final are that const must have a constant value known at compile time, while final can have a value assigned at run time but does not change after being initialized. Both are useful for optimizing performance and ensuring the immutability of certain values ​​in your code.

Again, I recommend avoiding the var keyword and the dynamic data type, preferably use final and the data type. At this stage it may not affect us much, but later when our code becomes more complex and does many more things, it becomes much easier to work with Dart as a statically typed language. But if you come from JavaScript, like me, or from another dynamically typed language, keep in mind that you can also do the same in Dart.

Wrap-up

In this first volume of our introduction to Dart, we have explored the fundamental concepts of variables and data types in Dart. In the next volumes of our series, we will take our knowledge one step further into the exciting world of programming with Dart. Stay tuned as we continue this journey of learning and discovery.

Thanks for reading, see you next time!