Dart Basics
Get an introduction to the basics of the Dart programming language, used for development with the Flutter SDK for mobile, web and beyond. By Jonathan Sande.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Dart Basics
35 mins
- Getting Started
- Why Dart?
- Core Concepts
- Variables, Comments and Data Types
- Comments
- Data Types
- Basic Dart Types
- The Dynamic Keyword
- Booleans
- Operators
- Arithmetic Operators
- Equality Operators
- Comparison Operators
- Logical Operators
- Strings
- Escaping Strings
- Immutability
- Nullability
- Null-Aware Operators
- Control Flow
- Conditionals
- If Statements
- Else Statements
- While Loops
- Testing the While Loop
- Trying Out the Do-While Loop
- Continue and Break
- For Loops
- Collections
- Lists
- Working With List Elements
- Maps
- Functions
- Defining Functions
- Working With Functions
- Nesting Functions
- Optional Parameters
- Named Parameters and Default Values
- Anonymous Functions
- Using Anonymous Functions
- Where to Go From Here?
Booleans
The bool
type holds values of either true
or false
.
bool areThereKittens = false;
print(areThereKittens); // false
But, if you look inside Schrödinger’s box, you might switch to having a real live kitten:
numberOfKittens = 1;
areThereKittens = true;
print(areThereKittens); // true
Run the code again to see your Boolean values in the console. It’s a good thing you looked in the box! :]
Operators
Dart has all the usual operators you’re familiar with from other languages like C, Swift and Kotlin.
Some examples of Dart’s operators include:
- arithmetic
- equality
- increment and decrement
- comparison
- logical
Next, you’ll take a look at each of these operators.
Arithmetic Operators
Arithmetic operators work just as you’d expect. Try them out by adding a bunch of operations to your DartPad:
print(40 + 2); // 42
print(44 - 2); // 42
print(21 * 2); // 42
print(84 / 2); // 42.0
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
Dart uses double-equals (==
) equality and not-equals (!=
) operators:
print(42 == 43); // false
print(42 != 43); // true
Comparison Operators
Dart uses the typical comparison operators:
- Less than (<)
- Greater than (>)
- Equal to (=>)
Here are some examples:
print(42 < 43); // true print(42 >= 43); // false
In addition, it also uses the usual compound arithmetic/assignment operators:
var value = 42.0;
value += 1; print(value); // 43.0
value -= 1; print(value); // 42.0
value *= 2; print(value); // 84.0
value /= 2; print(value); // 42.0
Compound arithmetic/assignment operators perform two tasks. +=
adds the value to the right to the variable on the left and then assigns the result to the variable.
A shortened form of += 1
is ++
:
value++;
print(value); // 43.0
And Dart has the usual modulo operator (%
) to return the remainder after one number has been divided by another:
print(392 % 50); // 42
392 ÷ 50 = 7.84, but where does that 42 in the result pane come from? It’s easier to see with long division.
Logical Operators
Dart uses the same logical operators as other languages, including &&
for AND and ||
for OR.
print((41 < 42) && (42 < 43)); // true
print((41 < 42) || (42 > 43)); // true
The negation operator is the exclamation mark, which turns false to true and true to false.
print(!(41 < 42)); // false
See the Dart documentation for a complete list of supported 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:
var firstName = 'Albert';
String lastName = "Einstein";
Similar to languages like Kotlin and Swift, 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:
var physicist = "$firstName $lastName likes the number ${84 / 2}";
print(physicist); // Albert Einstein
$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.
If there are special characters in the string, use \
to escape them:
var quote = 'If you can\'t explain it simply\nyou don\'t understand it well enough.';
print(quote);
// If you can't explain it simply
// you don't understand it well enough.
This example uses single quotes, so it needs an escape sequence, \'
, to embed the apostrophes for can’t and don’t into the string. You wouldn’t need to escape the apostrophe if you used double quotes instead.
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);
// If you can't explain it simply\nyou don't understand it well enough.
Here, Dart treated `\n`
as normal text because the string started with r
.
Click RUN in DartPad to see all your strings in the console.
Immutability
Dart uses the keywords const
and final
for values that don’t change.
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.
final
acts like val
in Kotlin or let
in Swift.You can use const
and final
in place of var
and let type inference determine the type:
const speedOfLight = 299792458;
print(speedOfLight); // 299792458
Here, Dart infers that speedOfLight
is an int
, as you can see in DartPad’s info panel.
final
indicates that a variable is immutable, meaning you can’t reassign final
values. You can explicitly state the type with either final
or const
:
final planet = 'Jupiter';
// planet = 'Mars';
// error: planet can only be set once
final String moon = 'Europa';
print('$planet has a moon, $moon');
// Jupiter has a moon, Europa
Nullability
In the past, if you didn’t initialize a variable, Dart gave it the value null
, which means nothing was stored in the variable. As of Dart 2.12, though, Dart joins other languages, like Swift and Kotlin, to be non-nullable by default.
Additionally, Dart guarantees that a non-nullable type will never contain a null value. This is known as sound null safety.
Normally, if you want to declare a variable, you must initialize it:
String middleName = 'May';
print(middleName); // May
Not everyone has a middle name, though, so it makes sense to make middleName
a nullable value. To tell Dart that you want to allow the value null
, add ?
after the type.
String? middleName = null;
print(middleName); // null
The default for a nullable type is null
, so you can simplify the expression to the following:
String? middleName;
print(middleName); // null
Run that and null
prints to the console.