Dart Basics
Dart Basics
Each Dart statement ends in a semicolon, just as statements do in C and Java. In the
code above, you’ve created a variable, myAge , and set it equal to 35.
You can use the built-in print in Dart to print the variable to the console. Add that
call after the variable:
print(myAge); // 35
Click RUN in DartPad to run the code. You’ll see the variable’s value, 35, prints in
the console.
VCS325-DART BASICS
Comments
Comments in Dart look just like those in C and in other languages: Text
following // is a single-line comment, while text within /* ... */ is a multi-line
comment block.
Here’s an example:
/*
*/
VCS325-DART BASICS
Data Types
Dart is statically typed, meaning that each variable in Dart has a type that
must be known when you compile the code. The variable type cannot change when
you run the program. C, Java, Swift and Kotlin are also statically typed.
If you don’t explicitly specify a data type, Dart uses type inference to try to
determine it, just like Swift and Kotlin do.
Dart also uses type inference for types other than int . Enter a variable, pi ,
equal to 3.14:
var pi = 3.14;
print(pi); // 3.14
VCS325-DART BASICS
Dart infers pi to be a double because you used a floating-point value to
initialize it. You can verify that in the Dart info panel by clicking pi .
Alternatively, instead of using type inference, you can declare the type.
int: Integers
bool: Booleans
VCS325-DART BASICS
int and double both derive from a type named num . num uses
the dynamic keyword to mimic dynamic typing in the statically typed Dart.
print(yourAge); // 27
If you use the dynamic keyword instead of var , you get what’s effectively a
dynamically typed variable:
dynamic numberOfKittens;
VCS325-DART BASICS
Here, you can set numberOfKittens to a String using quotes.
numberOfKittens has a type, since Dart has static typing. But that type is dynamic ,
which means you can assign other values with other types to it. So you can assign
an int value below your print statement.
numberOfKittens = 0;
print(numberOfKittens); // 0
numberOfKittens = 0.5;
print(numberOfKittens); // 0.5
VCS325-DART BASICS
Booleans
print(areThereKittens); // false
print(areThereKittens); // true
Operators
1. arithmetic
2. equality
4. comparison
VCS325-DART BASICS
5. logical
Arithmetic Operators
print(40 + 2); // 42
print(44 - 2); // 42
print(21 * 2); // 42
For division, even with integers, Dart infers the resulting variable to be a double .
That’s why you get 42.0 instead of 42 for the last print statement.
Equality Operators
VCS325-DART BASICS
Comparison Operators
Equal to (=>)
VCS325-DART BASICS
Logical Operators
Strings
The Dart string type is String . Strings are expressed in Dart using text surrounded
by either single or double quotes.
You can use either var and type inference or String to create a string variable, like
other types you’ve seen:
you can embed the value of an expression inside a string by using the dollar sign
symbol: ${expression}.
If the expression is an identifier, you can omit the { }. Add the following:
VCS325-DART BASICS
var physicist = "$firstName $lastName likes the number ${84 / 2}";
$firstName and $lastName are replaced by the variable values. The returns the
calculated result.
Escaping Strings
The escape sequences used in Dart are similar to those used in other C-like
languages. For example, you use \n for a new line.
var quote = 'If you can\'t explain it simply\nyou don\'t understand it well enough.';
print(quote);
VCS325-DART BASICS
If you need to show escape sequences within the string, you can use raw strings,
which are prefixed by r .
var rawString = r"If you can't explain it simply\nyou don't understand it well
enough.";
print(rawString);
Here, Dart treated `\n` as normal text because the string started with r .
Immutability
Dart uses the keywords const and final for values that don’t change.
VCS325-DART BASICS
Use const for values that are known at compile-time. Use final for values that don’t
have to be known at compile-time but cannot be reassigned after being initialized.
You can use const and final in place of var and let type inference determine the
type:
print(speedOfLight); // 299792458
Here, Dart infers that speedOfLight is an int , as you can see in DartPad’s info
panel.
VCS325-DART BASICS
// planet = 'Mars';
Nullability
print(middleName); // null
The default for a nullable type is null , so you can simplify the expression to the
following:
String? middleName;
VCS325-DART BASICS
print(middleName); // null
Control Flow
Control flow lets you dictate when to execute, skip over or repeat certain lines of
code. You use conditionals and loops to handle control flow in Dart.
Conditionals
While Loops
For Loops
Here’s what you need to know about control flow elements in Dart.
Conditionals
VCS325-DART BASICS
The most basic form of control flow is deciding whether to execute or skip over
certain parts of your code, depending on conditions that occur as your program runs.
The language construct for handling conditions is the if / else statement. if / else in
Dart looks nearly identical to its use in other C-like languages.
If Statements
Suppose you have a variable, animal , that’s currently a fox. It looks like this:
You can use an if statement to check whether animal is a cat or a dog, then run
some corresponding code.
Here, you’ve used the equality and OR operators to create a bool inside the
condition for the if statement.
VCS325-DART BASICS
Else Statements
With an else clause, you can run alternative code if the condition is false:
else {
You can also combine multiple if / else statements into an if / else if / else construct:
} else {
You can have as many else if branches between if and else as you need.
While Loops
VCS325-DART BASICS
Loops let you repeat code a certain number of times or based on certain conditions.
You handle condition-based repetition using while loops.
There are two forms of while loops in Dart: while and do-while . The difference is
that for while , the loop condition occurs before the code block. In do-while , the
condition occurs after. That means that do-while loops ensure the code block runs at
least one time.
var i = 1;
Next, use a while loop to print i while incrementing it. Set the condition to i is less
than 10:
print(i);
i++;
// 1
// 2
// 3
// 4
// 5
VCS325-DART BASICS
// 6
// 7
// 8
// 9
Run the code and you’ll see that the while loop prints the numbers 1 to 9.
i = 1;
do {
print(i);
i++;
// 1
// 2
// 3
// 4
// 5
// 6
VCS325-DART BASICS
// 7
// 8
// 9
The results are the same as before. This time, however, the loop body ran once
before checking the loop exit condition.
Dart uses continue and break keywords in loops and elsewhere. Here’s what they
do:
continue: Skips remaining code inside a loop and immediately goes to the
next iteration.
break: Stops the loop and continues execution after the body of the loop.
Be careful when using continue in your code. For example, if you take the do-
while loop from above, and you want to continue when i equals 5, that could result
in an infinite loop depending on where you place the continue statement:
i = 1;
do {
print(i);
if (i == 5) {
continue;
++i;
VCS325-DART BASICS
} while (i < 10);
// 1
// 2
// 3
// 4
// 5
// 5
// 5
// 5
// 5
// 5
// 5
// 5
// 5
// 5
// ...
The infinite loop occurs because, once i is 5, you never increment it again, so the
condition always stays true.
If you run this in DartPad, the infinite loop will cause the browser to hang. Instead,
use break , so the loop ends after i reaches 5:
VCS325-DART BASICS
i = 1;
do {
print(i);
if (i == 5) {
break;
++i;
// 1
// 2
// 3
// 4
// 5
Run the code. Now, the loop ends after five iterations.
For Loops
In Dart, you use for loops to loop a predetermined number of times. for loops
consist of initialization, a loop condition and an action. Once again, they’re similar
to for loops in other languages.
Dart also offers a for-in loop, which iterates over a collection of objects. You’ll
learn more about these later.
VCS325-DART BASICS
To see how a for loop works, create a variable for the sum:
var sum = 0;
Next, use a for loop to initialize a loop counter from i to 1. You’ll then check
that i is less than or equal to 10 and increment i after every loop.
Inside the loop, use a compound assignment to add i to the running sum:
sum += i;
Control Flow
VCS325-DART BASICS
Conditionals
While Loops
For Loops
Conditionals
The most basic form of control flow is deciding whether to execute or skip over
certain parts of your code, depending on conditions that occur as your program runs.
If Statements
Here, you’ve used the equality and OR operators to create a bool inside the
condition for the if statement.
Else Statements
With an else clause, you can run alternative code if the condition is false:
else {
VCS325-DART BASICS
// Animal is NOT a house pet.
You can also combine multiple if / else statements into an if / else if / else construct:
} else {
You can have as many else if branches between if and else as you need.
While Loops
There are two forms of while loops in Dart: while and do-while . The difference is
that for while , the loop condition occurs before the code block. In do-while , the
condition occurs after. That means that do-while loops ensure the code block runs at
least one time.
VCS325-DART BASICS
Testing the While Loop
print(i);
i++;
// 1
// 2
// 3
// 4
// 5
// 6
// 7
// 8
// 9
i = 1;
do {
print(i);
VCS325-DART BASICS
i++;
// 1
// 2
// 3
// 4
// 5
// 6
// 7
// 8
// 9
Dart uses continue and break keywords in loops and elsewhere. Here’s what they
do:
continue: Skips remaining code inside a loop and immediately goes to the
next iteration.
break: Stops the loop and continues execution after the body of the loop.
i = 1;
do {
VCS325-DART BASICS
print(i);
if (i == 5) {
continue;
++i;
// 1
// 2
// 3
// 4
// 5
// 5
// 5
// 5
// 5
// 5
// 5
// 5
// 5
VCS325-DART BASICS
// 5
// ...
The infinite loop occurs because, once i is 5, you never increment it again, so the
condition always stays true.
If you run this in DartPad, the infinite loop will cause the browser to hang. Instead,
use break , so the loop ends after i reaches 5:
i = 1;
do {
print(i);
if (i == 5) {
break;
++i;
// 1
// 2
// 3
// 4
// 5
VCS325-DART BASICS
Run the code. Now, the loop ends after five iterations.
For Loops
sum += i;
Collections
Collections are useful for grouping related data. Dart includes several different types
of collections, but this tutorial will cover the two most common
ones: List and Map .
Lists
Lists in Dart are similar to arrays in other languages. You use them to maintain an
ordered list of values. Lists are zero-based, so the first item in the list is at index 0:
VCS325-DART BASICS
Here’s a list of different desserts:
You enclose the elements of a list in square brackets: [ ] . You use commas to
separate the elements.
At the beginning of the line, you can see that the type is List . You’ll notice there is
no type included. Dart infers that list has type List .
Click numbers in DartPad and you’ll see that Dart recognizes the type as
a List of int .
VCS325-DART BASICS
Working With List Elements
To access the elements of a list, use subscript notation by putting the index number
between square brackets after the list variable name. For example:
print(firstDessert); // cookies
Since list indices are zero-based, desserts[0] is the first element of the list.
desserts.add('cake');
print(desserts);
desserts.remove('donuts');
print(desserts);
VCS325-DART BASICS
Earlier, you learned about for loops. Dart’s for-in loop that works especially well
with lists. Try it out:
You don’t need to use an index. Dart just loops through every element
of desserts and assigns it each time to a variable named dessert .
Getting hungry? Well, you can’t have any dessert until you’ve finished your
vegetables. :]
Maps
VCS325-DART BASICS
When you want a list of paired values, Map is a good choice. Dart Map s are similar
to dictionaries in Swift and maps in Kotlin.
'cake': 500,
'donuts': 150,
'cookies': 100,
};
You surround Map s with curly braces { } . Use commas to separate a map’s
elements.
Elements of a map are called key-value pairs, where the key is on the left of a colon
and the value is on the right.
You find a value by using the key to look it up, like this:
print(donutCalories); // 150
VCS325-DART BASICS
The key, 'donuts' , is inside the square brackets after the map name. In this case, it
maps to a value of 150 .
Click donutCalories in DartPad and you’ll see that the inferred type is int? rather
than int . That’s because, if a map doesn’t contain the key that you’re looking up,
it’ll return a null value.
Add a new element to a map by specifying the key and assigning it a value:
calories['brownieFudgeSundae'] = 1346;
print(calories);
Run that code and you’ll see the map printed in horizontal format with your new
dessert at the end.
Functions
Functions let you package multiple related lines of code into a single body. You then
summon the function to avoid repeating those lines of code throughout your Dart
app.
VCS325-DART BASICS
A function consists of the following elements:
Return type
Function name
Defining Functions
The code you’re turning into a function goes inside the curly brackets. When you
call the function, you pass in arguments that match the types of the parameters of
the function.
Next, you’ll write a new function in DartPad that will check to see if a given string
is banana:
The function uses return to return a bool . The argument you pass to the function
determines the bool .
VCS325-DART BASICS
This function will always return the same value type for any given input. If a
function doesn’t need to return a value, you can set the return type
to void . main does this, for example.
You can call the function by passing in a string. You might then pass the result of
that call to print :
void main() {
print(isBanana(fruit)); // false
Nesting Functions
Typically, you define functions either outside other functions or inside Dart classes.
However, you can also nest Dart functions. For example, you can
nest isBanana inside main .
void main() {
VCS325-DART BASICS
print(isBanana(fruit)); // false
You can also change the argument you to a function, then call it again with the new
argument:
fruit = 'banana';
print(isBanana(fruit)); // true
The result of calling the function depends entirely on the arguments you pass in.
Optional Parameters
If a parameter to a function is optional, you can surround it with square brackets and
make the type nullable:
if (title == null) {
} else {
In this function, title is optional. It will default to null if you don’t specify it.
VCS325-DART BASICS
Now, you can call the function with or without the optional parameter:
print(fullName('Joe', 'Howard'));
// Joe Howard
These parameters are optional by default, but you can give them default values or
make them required by using the required keyword:
value is required, while min and max are optional with default values.
With named parameters, you can pass in arguments in a different order by supplying
the parameter names with a colon:
VCS325-DART BASICS
You can leave off the parameters with default values when calling the function.
Anonymous Functions
Dart supports first-class functions, meaning that it treats functions like any other
data type. You can assign them to variables, pass them as arguments and return them
from other functions.
To pass these functions around as values, omit the function name and return type.
Since there’s no name, this type of function is called an anonymous function.
You can assign an anonymous function to a variable named onPressed , like so:
final onPressed = () {
VCS325-DART BASICS
print('button pressed');
};
onPressed has a value of type Function . The empty parentheses indicate the
function has no parameters. Like regular functions, the code inside the curly brackets
is the function body.
To execute the code within the function body, call the variable name as if it were the
name of the function:
You can simplify functions whose body only contains a single line by using arrow
syntax. To do this, remove the curly brackets and add a fat arrow => .
final onPressed = () {
print('button pressed');
};
// refactored
VCS325-DART BASICS
Using Anonymous Functions
You’ll often see anonymous functions in Flutter, like those above, passed around as
callbacks for UI events. This lets you specify the code that runs when a user does
something, like pressing a button.
Another common place where you’ll see anonymous functions is with collections.
You can give a collection an anonymous function that will perform some task on
each element of the collection. For example:
// 1
// 2
// 3
);
// 4
2. .map takes all the list values and returns a new collection with them.
3. An anonymous function is passed as a parameter. In that anonymous function,
you have a drink argument that represents each element of the list.
4. The body of the anonymous function converts each element to uppercase and
returns the value. Since the original list is a list of strings, drink also has
type String .
VCS325-DART BASICS
Using an anonymous function and combining it with .map is a convenient way to
transform one collection into another.
Note: Don’t confuse the .map method with the Map type.
VCS325-DART BASICS