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.

4.6 (19) · 2 Reviews

Download materials
Save for later
Share
You are currently viewing page 3 of 5 of this article. Click here to view the first page.

Null-Aware Operators

Dart has some null-aware operators you can use when you’re working with null values.

The double-question-mark operator, ??, is like the Elvis operator in Kotlin: It returns the left-hand operand if the object isn’t null. Otherwise, it returns the right-hand value:


var name = middleName ?? 'none';

print(name); // none

Since middleName is null, Dart assigns the right-hand value of 'none'.

The ?. operator protects you from accessing properties of null objects. It returns null if the object itself is null. Otherwise, it returns the value of the property on the right-hand side:

print(middleName?.length); // null

In the days before null safety, if you forgot the question mark and wrote middleName.length, your app would crash at runtime if middleName was null. That’s not a problem anymore, because Dart now tells you immediately when you need to handle null values.

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.

In this section, you’ll learn more about:

  • Conditionals
  • While Loops
  • Continue and Break
  • For Loops

Here’s what you need to know about control flow elements in Dart.

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.

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:

var animal = 'fox';

Fox

You can use an if statement to check whether animal is a cat or a dog, then run some corresponding code.

if (animal == 'cat' || animal == 'dog') {
  print('Animal is a house pet.');
}

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 {
  print('Animal is NOT a house pet.');
}
// Animal is NOT a house pet.

You can also combine multiple if/else statements into an if/else if/else construct:

if (animal == 'cat' || animal == 'dog') {
  print('Animal is a house pet.');
} else if (animal == 'rhino') {
  print('That\'s a big animal.');
} else {
  print('Animal is NOT a house pet.');
}
// Animal is NOT a house pet.

You can have as many else if branches between if and else as you need.

While Loops

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.

Testing the While Loop

To try this out, create a variable i initialized to 1:

var i = 1;

Next, use a while loop to print i while incrementing it. Set the condition to i is less than 10:

while (i < 10) {
  print(i);
  i++;
}
// 1
// 2
// 3
// 4
// 5
// 6
// 7
// 8
// 9

Run the code and you’ll see that the while loop prints the numbers 1 to 9.

Trying Out the Do-While Loop

Reset i in DartPad, then add a do-while loop:

i = 1;
do {
  print(i);
  i++;
} while (i < 10);
// 1
// 2
// 3
// 4
// 5
// 6
// 7
// 8
// 9

The results are the same as before. This time, however, the loop body ran once before checking the loop exit condition.

Continue and Break

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;
} 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:

i = 1;
do {
  print(i);
  if (i == 5) {
    break;
  }
  ++i;
} while (i < 10);
// 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.

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:

for (var i = 1; i <= 10; i++) {
  sum += i;  
}
print("The sum is $sum"); // The sum is 55

Run your code in DartPad to see the sum.

Dart for loop