Chapter 1. Learning Dart Variables
In this chapter, we focus on learning the basics of using variables in Dart. As you might expect, Dart offers a rich set of variable data types. To quickly get up to speed in the language, it is vitally important to know the basic data types.
If you are familiar with the use of variables in other programming languages, understanding variables in Dart should not be too difficult to grasp. Use this chapter as a quick guide to cement your understanding before moving on to more complex topics.
For beginners, this chapter will introduce you to the fundamentals. Ultimately it should offer a quick technical guide as you progress in your journey to learn Dart/Flutter.
Across the chapter, the code examples are self-contained and are focused on a typical use case. We start by discussing the four main variable types (i.e., int
, double
, bool
, and String
) and how each is used. Finally, we learn how to let Dart know what we want to do with our variables (i.e., final
, const
, and null
).
We also cover the subject of immutability, which refers to the ability to change the value associated with a variable. An immutable variable is one that cannot be changed. In Dart, the keywords const
and final
make a variable immutable . A key nuance of immutability is whether the variable is checked at compile time or runtime. Compile time refers to checks applied at the code building stage (i.e., const
variables). Runtime refers to checks performed at the application execution stage (i.e., final
variables).
As of Dart 2.0, the language is type-safe, meaning that once a variable is declared, the type cannot be changed. For example, if a variable of type double is declared, it cannot then be used as an int without explicit casting. Before we dive into how to use variables, we need to ensure the programming environment is correctly set up.
1.1 Running a Dart Application
Solution
Dart code can be run within your environment once the SDK has been installed. To learn how to install the SDK, see the Appendix. Open a terminal session to allow the entry of commands. If you are using an IDE, the terminal needs to be opened within that application. Now confirm that Dart is installed on the device by checking the version as shown here:
dart--version
If the command responds successfully, you should see the version of the SDK installed and the platform you are running on. If the command is unsuccessful, you will need to check the installation and path for your device.
Now, in your editor, create a new file named main.dart and add the following contents:
void
main
()
{
(
'Hello, Dart World!'
);
}
Run your example code from the command line as follows:
dartmain.dart
This command should output âHello, Dart World!â
Discussion
The dart
command is available as part of the Dart SDK installation. In the preceding example, the command will run a file named main.dart. Dart applications have the extension .dart and can be run either from the command line or within an IDE (e.g., Android Studio or VS Code). Note: neither Android Studio nor VS Code are preconfigured to include Dart/Flutter functionality. You will need to install the relevant plug-in (in addition to installing the SDK) before being able to run any code.
If you donât want to install Dart within your environment, use the online editor available at DartPad.
If you are unable to run the dart
command, itâs likely that the SDK has not been installed correctly. Use the latest installation instructions to confirm the installation on your device.
1.2 Working with Integer Values
Solution
Use an integer variable to store a number without a decimal point.
If you want to store an integer value of 35, the declaration would be as follows:
void
main
()
{
int
myVariable
=
35
;
(
myVariable
);
}
In the Dart language, an integer uses the reference int
. In the preceding code example, the data type (e.g., int
) is the first part of the declaration. Next, a label is assigned to the data type to be used, e.g., myVariable
. Finally, we assign a value to the data typeâin this example, the value of 35.
To use the data type, a variable is declared, e.g., myVariable
. A variable is a label used to reference the data type created.
Once a variable is available, you can assign a value to the data type. In the example, the integer 35
is assigned to the variable myVariable
. A print
statement is then used to output the variable value.
Discussion
Dart follows a set pattern for declaration of variables. The prefix declares the data type to be used; this is followed by a variable label and then an optional assignment.
In this example, the data type to be used is an int
. An integer is represented by numbers that do not have a decimal point. The typical use case for an int
is a number that doesnât require a decimal point (i.e., precision). An integer is defined as a 64-bit integer number. The integer data type is a subtype of num
, which includes basic operations, e.g., +/â, etc.
The variable label provides a means to reference the int
data type in the example code. Our example uses the label myVariable
. When naming a variable, try to make the name relevant to the purpose of the variable.
To complete the variable declaration, a value is assigned. Here we assign the value of 35
to our variable, meaning when we reference this, we expect the value of 35 to be used for our int
data type.
If the integer variable were not initialized, it would mean a value could not be accessed. In this situation, Dart will return an error indicating the value we are trying to access is a non-nullable variable. Essentially, this means we have not assigned a value to a variable we are attempting to access. In most instances, this is an error, and the Dart compiler will helpfully tell us we have made a mistake. If you do in fact wish to use a nullable variable, you would need to tell Dart how to handle this situation. Learn more about handling null values in Recipe 1.9.
1.3 Working with Double Values
Problem
You want to store a number with a decimal point.
Solution
Use a double (precision) variable to store a number including a decimal point.
If you want to store a double value of 2.99, declare the following:
void
main
()
{
double
myVariable
=
2.99
;
(
myVariable
);
}
Similar to other variables, prefix the variable with the desired data type, e.g., double
. The variable will then require a label to be assigned, e.g., myVariable
. Finally, assign a value to the data typeâin this example, the value of 2.99.
Discussion
In the previous example, we begin by indicating the data type to be used, i.e., double
. Following that, we provide a variable name (in our example, myVariable
) for double
. The last part, where a value is assigned to the variable, is optional.
The typical use case for a double data type is a number requiring a level of precision. A double data type is a 64-bit floating-point number. Double is a subtype of num
, which includes basic operations, e.g., +/â, etc.
1.4 Working with Boolean Values
Solution
Use a bool
variable to store a true/false state.
Declare a Boolean variable using the keyword bool
, following the data type declaration with a label for the variable name, e.g., myVariable
. Finally, assign a value to the variable of either true
or false
.
Hereâs an example of how to declare a bool
:
void
main
()
{
bool
myVariable
=
true
;
(
myVariable
);
}
Discussion
In the preceding example, we begin by indicating the data type to be used, i.e., bool
. Following that, we provide a variable name for the defined data type. The last part is optional, where we assign a value to the named variable.
The use case for a bool
is that of a true/false scenario. Note that true
and false
are reserved keywords in Dart. Reserved in this context indicates the word has a defined meaning in terms of the language. A boolean data type includes logic operations, e.g., and, equality, inclusive or, exclusive or.
1.5 Working with Strings
Discussion
Begin by indicating the data type to be used, i.e., String
. A string is used to represent a sequence of characters that can be both numbers and letters. Note that a String uses a capital for its data type, which is often the source of errors when first learning Dart.
The data type will require a variable for the defined data type, and this will be used to reference the associated value. An assignment of a value is optional at this stage.
The typical use case for a String
data type is collection of text. A String
data type in Dart uses 16-bit Unicode Transformation Format (UTF-16) code units. The String
class is used to represent text characters but due to encoding can also support an extended range of characters, e.g., emojis.
When using a String
variable, you can use either matching single or double quotes to identify the text to be displayed. If you require a multiline text, this can be achieved using triple quotes. In the example, you can see a demonstration of both of these types of declaration.
1.6 Printing Information to the Console
Solution
Use a print
statement to display information from an application. The print
statement can display both static (i.e., a string literal) and variable content.
Hereâs an example of how to print static content:
void
main
()
{
(
'Hello World!'
);
}
Hereâs an example of how to print the content of a variable:
void
main
()
{
int
intVariable
=
10
;
var
boolVariable
=
true
;
(
intVariable
);
(
'
$
intVariable
'
);
(
'The bool variable is
$
boolVariable
'
);
}
Discussion
Use the $
character to reference a variable in a print
statement. Prefixing a variable with the $
tells Dart that a variable is being used and it should replace this value.
The print
statement is useful in a number of scenarios. Printing static content doesnât require any additional steps to display information. To use with static content, enclose the value in quotes and the print
statement will take care of the rest.
Printing a variable value will require the variable to be prefixed with the $
sign. Where Dart is being used to print content, you can tell the language that you want the value to be displayed. In the second example, you see three common ways to reference a variable in a print
statement.
Dart will provide feedback on whether a brace is required; typically it is not. However, if you create a complex variable type, do check to ensure you are referencing the element desired.
1.7 Adding a Constant Variable (Compile Time)
Problem
You want to create a variable that cannot be changed (immutable) at any point.
Solution
Use const
to create a variable whose value cannot be reassigned and will be checked at compile time.
Hereâs an example of using a const
variable:
void
main
()
{
const
daysInYear
=
365
;
(
'There are
$
daysInYear
days in a year'
);
}
Discussion
In Dart, const
represents a value that cannot be changed.
Use the const
keyword where a variable is not subject to change. The example declares a const
variable set to the number 365
, meaning it is immutable across the scope of the application.
If you were to try to change the value within the application, you would see a compile time error indicating an assignment cannot be made due to the variable being designated as a const
. Remove the comment associated with the line featuring daysâInâYear = 10
to see this type of error.
The use of const
is a good method to reduce errors within your application. Declaring variables as const
provides a robust interface that uses the compiler to explicitly verify the use of variables.
1.8 Adding a Constant Variable (Runtime)
Discussion
Final
represents a value that needs to be determined at runtime and is not subject to change. The final
keyword is used in situations where a value is derived at runtime (i.e., when the application is active). Again, the value assigned is immutable; however, unlike a const
value, it cannot be known at compile time.
If you attempt to perform an assignment to a final
variable that has already been set, the compiler will generate an error.
In the code example, the day output by the print
statement is returned by the DateTime
function. The value returned is determined when the application is run, so it will display based on the actual weekday available on the host machine.
1.9 Working with Null Variables
Solution
Use null
to apply a consistent value to a declared variable. Null is an interesting concept, as it is meant to represent the absence of content. Typically a null value is used to initialize variables that do not have a default value to be assigned. In this instance null
can be used to represent a variable that has not explicitly been assigned a value.
Hereâs an example of how to declare a variable as null in Dart:
void
main
(){
int
?
myVariable
;
(
'ten:
$
myVariable
'
);
myVariable
=
10
;
(
'ten:
$
myVariable
'
);
}
Discussion
To enable null
to be assigned to a data type, it is expected that the ?
type is appended to explicitly indicate a value can also be null. In the example, myVariable
is set to nullable by prefixing the variable with ?
.
In Dart, null
is also an object, which means it can be used beyond the simple âno valueâ use case. More recent versions of the Dart SDK also require explicit acknowledgment of whether a data type is nullable or non-nullable.
Note that as of Dart v2.0, null
type safety is now the default, meaning it is no longer possible to assign null
to all data types.
For further information, consult the Null
class reference in the Dart API.
Get Flutter and Dart Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.