Book Image

Learning Dart

Book Image

Learning Dart

Overview of this book

Table of Contents (19 chapters)
Learning Dart
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Changing the execution flow of a program


Dart has the usual control structures with no surprises here (refer to control.dart).

An if...else statement (with an optional else) is as follows:

var n = 25;
if (n < 10) {
  print('1 digit number: $n');
} else if (n >=  10 && n < 100){
  print('2+ digit number: $n'); // 2+ digit number: 25
} else {
  print('3 or more digit number: $n');
}

Single-line statements without {} are allowed, but don't mix the two. A simple and short if…else statement can be replaced by a ternary operator, as shown in the following example code:

num rabbitCount = 16758;
(rabbitCount > 20000) ? print('enough for this year!') : print('breed on!');   // breed on!

If the expression before ? is true, the first statement is executed, else the statement after : is executed. To test if a variable v refers to a real object, use: if (v != null) { … }.

Testing if an object v is of type T is done with an if statement: if (v is T).

In that case we can safely cast v to...