Control Flow statement on Dart — Dart Programming — Part 6

Hoang Nguyen
6 min readApr 22, 2022

--

Hi guys. After a day break i’m come back to bring about control flow statement. I think we have only few stories on Dart basic, maybe one story to talk about null-safety in Dart before we get start with Flutter Framework. Okay, come and FlutterWithMe!

What’s control flow in programming ?

The control flow is the order in which the computer executes statements in a script.

Code is run in order from the first line in the file to the last line, unless the computer runs across the (extremely frequent) structures that change the control flow, such as conditionals and loops.

Example:

if (isRaining()) {
you.bringRainCoat();
} else if (isSnowing()) {
you.wearJacket();
} else {
car.putTopDown();
}

In Dart you can control the flow by using any of the following:

Conditional statement

First and simple is “if-else” statement.

For example on our conversation, it’s look like.

If today is rainning, i’ll bring rain coat. But if today is snowing, i’ll wear jacket. Or else i’ll wear a t-shirt and jean for walking.

And we’ll convert it into code:

if(isRaining){
bringRainCoat();
}else if(isSnowing){
wearJacket();
}else{
wearShirtAndJeanWalking();
}

But what happen when you have too many condition to check like status: “pending,proccessing,fail,success,deleted,forward”. Well, you also can use if-else statement, but it’ll look like this.

String status = "pending";if (status == "pending") {
} else if (status == "processing") {

} else if (status == "fail") {

} else if (status == "success") {

} else if (status == "deleted") {

} else if (status == "foward") {

} else {

}

It’s nightmare when you have too many if else like this. Because of that, we’ve switch statement when you have too many condition.

var command = 'OPEN';
switch (command) {
case 'CLOSED':
executeClosed();
break;
case 'PENDING':
executePending();
break;
case 'APPROVED':
executeApproved();
break;
case 'DENIED':
executeDenied();
break;
case 'OPEN':
executeOpen();
break;
default:
executeUnknown();
}

Alway have default case when it don’t match with anycase in your switch statement. But what happen when you have two case that need do the same function ? Don’t worry, i’ll tell you right away. Look at that.

var command = 'OPEN';
switch (command) {
case 'CLOSED':
case 'CLOSEDSECONDFLOOR':
executeClosed();
break;
case 'PENDING':
executePending();
break;
case 'APPROVED':
executeApproved();
break;
default:
executeUnknown();
}

See, all you have to do is write two case you need function step by step, it’ll do the function in same two case. Another trick i want to tell you is try using Enum when work with conditional statement. It’ll save your time too much.

Status status = Status.pending;switch(status){
case Status.pending:
// TODO: Handle this case.
break;
case Status.process:
// TODO: Handle this case.
break;
case Status.fail:
// TODO: Handle this case.
break;
case Status.success:
// TODO: Handle this case.
break;
case Status.delete:
// TODO: Handle this case.
break;
case Status.foward:
// TODO: Handle this case.
break;
default:
break;
}

You won’t miss any case, and no afraid to write mistake string or int. Very powerful.

Other one is “assert” which only worked in development mode for helping disrupt normal execution if a boolean condition is false.

assert(number<100);//Customize error message, add a string as the second agrument to asserts (it's optionally with a trailling comma)
assert(number<100, "Number must be smaller than 100");

Next one is Loops statement

Simple is for loops, you can write a loop like this

for(var int i = 0; i < 5;i++){
print("i value: $i");
}

This code mean: you write a loop that start with i = 0 and run until i == 5, i’ll stop. After one time doing function print, it’ll increase i with i++;

How about forEach loop ?

List<int> listNumber = [1,6,2,7,34,7,4,3,2];listNumber.forEach((int value){
print("number: $value");
});

With this way, you will loops every value inside list until end.

So the difference between for and forEach :

  • For loop : use when you know the end of the loop.
  • ForEach loop : use when you don’t know the end of the loop.

On dart we can use for … in instead of forEach. with for you actually know the index of this item inside list, but with forEach or for…in you only know the value.

List<int> listNumber = [1,6,2,7,34,7,4,3,2];for(int numberValue in listNumber){
print("number value: $numberValue");
}
Result:
number value: 1
number value: 6
number value: 2
number value: 7
number value: 34
number value: 7
number value: 4
number value: 3
number value: 2

While and do-while

A while loop will process function inside loop until you break it or it’ll be forever.

int i = 0;
bool isFinish = false;
while (!isFinish) {
print("Value: $i");
i++;
isFinish = i == 10;
}

It’ll loop until i == 10 and then stop because we set value isFinish is true. This is how while loop work.

This is do-while loop

int i = 0;
bool isFinish = false;
do{
print("Value: $i");
i++;
isFinish = i == 10;

}
while (!isFinish);

Difference between do-while and while is :

While loop checks the condition first and then executes the statement(s), whereas do while loop will execute the statement(s) at least once, then the condition is checked.

Break & Continue

  • “break” is using to stop looping.
int i = 0;
bool isFinish = false;
while (!isFinish) {
if (i == 5) ;
break;
print("Value: $i");
i++;
isFinish = i == 10;
}
  • “continue” is using to skip to the next loop iteration.
for (int i = 0; i < candidates.length; i++) {
var candidate = candidates[i];
if (candidate.yearsExperience < 5) {
continue;
}
candidate.interview();
}

Exceptions

You can throw and catch exceptions in Dart. Exceptions are errors indicating that something unexpected happened. Like this one.

throw FormatException("This is format error exception");

or you can also throw arbitrary objects:

throw 'Out of llamas!';

Remember catch (or capturing) error when throw. Catching an exception gives you a chance to handle it:

try {
breedMoreLlamas();
} on OutOfLlamasException {
// A specific exception
buyMoreLlamas();
} on Exception catch (e) {
// Anything else that is an exception
print('Unknown exception: $e');
} catch (e) {
// No specified type, handles all
print('Something really unknown: $e');
}

On catch() have two parameter, first is exception that was thrown, second is the StackTrace object.

try {
// ···
} on Exception catch (e) {
print('Exception details:\n $e');
} catch (e, s) {
print('Exception details:\n $e');
print('Stack trace:\n $s');
}

Finally

To make sure that some code that will run even it get error. We using finally block. Finally clause runs after any matching catch clauses:

try {
breedMoreLlamas();
} catch (e) {
print('Error: $e'); // Handle the exception first.
} finally {
cleanLlamaStalls(); // Then clean up.
}

I think that’s all to talk about control flow. It’s only in dart basic so maybe you’ll see more complex syntax. If have any question, please let me know so we can discuss it. Thanks for your reading time!

--

--

Hoang Nguyen
Hoang Nguyen

Written by Hoang Nguyen

I've started with Flutter since 2019 and have good knowledge about Flutter and some architecture. I want to share more of my knowledge and learn more from other

No responses yet