Dart

Type Inference Variable in Dart | Dart Tutorial #2

Welcome, everyone! In this article, we’ll dive into the Type Inference Variable in Dart programming language.

Dart is very smart, which is why it holds the tag of a modern programming language. One of the best features of Dart is Type Inference.

Type Inference refers to the ability of the Dart compiler to automatically deduce the type of a variable based on the value assigned to it. This means that Dart can figure out whether you are talking about text, a whole number, or a decimal number without you always having to specify it explicitly.

Type inference makes your code cleaner and easier to read while still being smart enough to understand what you mean.

Implicit and Explicit.

To learn the Dart programming language from scratch, the first thing you need to do is focus while reading this article or practicing because your time is valuable. If you stay focused and keep away from distractions, I promise you that you’ll become a full-stack app developer with Flutter.

Now, the purpose of saying this is to draw your attention to a word I mentioned above: “explicitly.” It’s important to understand what this word means and why I highlighted it. There are two key concepts in Dart: implicit and explicit.

When something happens implicitly, it means that it happens automatically without you having to do anything extra. Dart, the programming language, handles some tasks for you behind the scenes.

When something happens explicitly, it means you have to give clear, direct instructions to Dart. You need to spell things out.

We often see implicit and explicit behavior in declaring variables. Let’s take an example of implicit declaration where Dart infers the type automatically:

var a = 10;
var b = "Hello";

Dart knows that a is an integer (int) and b is a string without you saying it.

In explicit declaration, you have to give clear, direct instructions to Dart:

int number = 42; // You're telling Dart "number is an int"

Naming Data

At its simplest, computer programming is all about manipulating data, since everything you see on your screen can be reduced to number. 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,

When you write Dart code, you can give names to pieces of data so you can easily refer to them later. Think of it like labeling boxes in a storage room so you know what’s inside each one without having to open them.

Variables

Take a look at the following:

int number = 10;

This statement declares a variable called number of type int.
It then sets the value of the variable to the number 10. The int part of the statement is known as a type annotation, which tells Dart explicitly what the type is.

If you want to change the value of a variable, then you can just give it a different value of the same type:

int number = 10; 
number = 15; 

For readers who are familiar with object-oriented programming, you’ll be interested to learn that 10, 3.14159 and every other value that you can assign to a variable are objects in Dart, In fact, Dart doesn’t have the primitive variables types that exits in some langauge. Everything is an object. Although int and double look like primitives, they’re subclasses of num, which is a subclass of Object.

Note

With numbers as object, this lets you do some interesting things:

10.isEven
//true
3.14159.round()
//3

Dart treats all values, including numbers, as objects.

Let’s go through the different types of variables in Dart

  1. int (Integer)
    • This type is used for whole numbers without any decimal point.
      Example: Numbers like 1, 2, 42, -10
  2. double
    • This type is used for numbers that have a decimal point.
      Example: Numbers like 3.14, 0.99, -2.5.
  3. string
    • This type is used for text.
      Example: Words or sentence like ‘hello’, ‘Dart is fun!’, “12345”.
  4. bool (Boolean)
    • This type is used for true/false values.
      Example true or false
  5. List
    • This type is used for an ordered collection of items, like an array.
      Example: A list of numbers, words, or any other data type.
  6. Map
    • This type is used of a collection of key-value pairs.
      Example: A dictionary where you can look up values using keys.
  7. Set
    • This type is used for an unordered collection of unique items.
      Example: A collection where each item appears only once.
  8. var
    • This keywords lets Dart decide the type for you based on the values you assign.
      Example: You can use var for any type, and Dart will figure it out.
  9. dynamic
    • This type can hold any kind of data, and you can change it later.
      Example: Use dynamic if you don’t know what type of data you’ll have or if it can change.
  10. const and final
    • These keywords are used to declare variables whose values won’t change.
      • const if for compile-time constant (value known at compile time).
      • final is for variables that are set once never change.

Type Safety

Type Safety means that the programming langauge make sure you use variables in the right way. It helps prevent errors by ensuring that each variable only holds the kind of data it’ supposed to.

Once you tell Dart what a variable’s type is, you can’t change it later. Here’s an example:

int myInteger = 10; 
my Integer = 3.14159; // No. That's not allowed. 

3.14159 is a double, but you already defined myInteger as an int. No changes allowed!

Dart’s type safety will save you countless hours when coding, since the compiler will tell you immediately whenever you try to give a variable the wrong type. This prevents you from having to chase down bugs after you experience runtime crashes.

Of course, sometimes it’s useful to be able to assign related types to the same variable. That’s sill possible. For example, you could solve the problem above, where you want myNumber to store both an integer and floating-point value, like so:

num myNumber; 
myNumber = 10;  //Ok
myNumber = 3.14159; //Ok
myNumber = "Ten"; // No, That's not allowed. 

The num type can be either an int or a double, so the first two assignments work. However, the string value “Ten” is of a different type, so the compiler complains.

Now, if you like living dangerously, you can throw safety to the wind and use the dynamic type. This lets you assign any data type you like to your variable, and the compiler won't warn you about anything. 
dynamic myVariable; 
myVariable = 10; //ok
myVariable = 3.14159; //ok
myVariable = "ten"; //ok

But, honestly, don’t do that. Friends don’t let friends use dynamic. Your life is too valuable for that.

Type inference

Dart is smart in a lot of ways, you don’t even have to tell it the type of a variable, and Dart can still figure out what you mean. The var keyword says to Dart, “Use whatever type is appropriate.”

var someNumber = 10;

There’s no need to tell Dart that 10 is an integer. Dart infers the type and makes someNumber an int. Type safety still applies, though:

var someNumber = 10;  //Ok
someNumber = 15; //Ok
someNumber = 3.14159; //No, That's not allow.

Trying to set someNumber to a double will result in an error.
Your program won’t even compile. Quick catch; time saved.
Thanks, Dart!

Constants

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 the two.

const constants

Variables whose value you can change are knows as mutable data.
For example, if you declare int number = 10;, you can later change number to a different value like 0 or 15.
Mutables certainly have their place in programs, but can also preset 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 variables whenever possible.
These unchangeable variables are known as immutable data.

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

const myConstant = 10; 

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.
For example, consider the following example:

const myConstant = 10; 
myConstant = 0; // Not allowed.

This code produces an error:

Constant variables can't be assigned a value.

Constants can be optimized by Dart because their values are known at compile time. This can lead to performance improvements in your program.

final constants

Often, you know you’ll want a constant in your program, but you don’t know what its value is at compile time. You’ll only know the value after the program starts running. This kind of constant is knows as runtime constant.

In Dart const is only used for compile-time constants; that is, for values that can be determined by the compiler before the program ever starts running.

If you can’t create a const variable because you don’t know its value at compile time, then you must use the final keyword to make it a runtime constant. There are many reasons you might not know a value until after your program is running. For example, you might need to fetch a value from the server, or query the device settings, or ask a user to input their age.

Here is another example of runtime value:

final hoursSinceMidnight = DateTime.now().hour;

DateTime.now() is a Dart function that tells you the current date and time when the code is run. Adding hour to that tells you the number of hours that have passed since the beginning of the day. Since that code will produce a different results depending on the time of day, this is most definitely a runtime value. So to make hoursSinceMidnight a constant, you must use the final keyword instead of const.

If you try to change the final constant after it’s already been set:

hoursSinceMidnight = 0;

This will produce the following error:

The final variable 'hoursSinceMidnight' can only be set once.

You don’t actually need to worry too much about the
difference between const and final constants. As a general
rule, try const first, and if the compiler complains, then
make it final. The benefit of using const is it gives the
compiler the freedom to make internal optimizations to the
code before compiling it.
No matter what kind of variable you have, though, you
should give special consideration to what you call it.

If you’re eager to dive into Dart and wondering how to start your projects flawlessly, my previous article on Dart’s core concepts is a must-read. It will guide you through creating projects in Dart with precision, accelerating your learning and boosting your Dart skills significantly.
Dart Tutorial | Learn Dart from Scratch #1

4 thoughts on “Type Inference Variable in Dart | Dart Tutorial #2

Leave a Reply

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

Back To Top