Dart Apprentice — Part I

Hamed Seify
CodeX
Published in
13 min readAug 16, 2021

One of the newest technology in developing cross-platforms softwares is Flutter, that not only can use to develop IOS and Android apps, but also can be used to develop desktops softwares such as Windows and Linux and Macos.

In this article I’m going to present a summary of Dart Apprentice book by Raywenderlich, that is really good book for both Android and IOS developers that want to migrate to developing Flutter. It’s even good for programmers who want to start mobile application developing and they have not enough experience in Android or IOS. As I told I’m going to present a summary, so if you want to learn more deep, you should refer to book and read it complete. In addition there is more detail in book that was not possible to bring here.

What is Dart and how can be used?

Dart is a general purpose programming language developed by Google. What is this mean? It means that once you learn dart, you can use Dart for mobile and website and desktops softwares, and you don’t need to learn more programming languages such as Kotlin and Swift and C# and some others.

In the following I’m going to speak about dart syntax and you need a tool to test and try these snippets. There are some tools that easily you can access or most probably you have and use them. First tool is DartPad that is a browser-based tool you can access it via below link:

DartPad is useful because of it’s ready to use. It means that you don’t need to install any SDK or plugin or another accessories.

Add alt text

The second one is Intellij IDEA, one of the best IDE’s I have seen. On behalf of the author of the book, I want to recommend it because you won’t need any more tools. VScode by Microsoft is the final that is a pretty good tool to developing code. Like Intellij, VScode is useful too for other languages and if you want to test them you can keep using it. Although this book recommend Intellij to you, but the author will use VScode because of its lightweight and simple interface.

Now we are ready to test Dart commands.

Comments:

Programming start by expressions. Some sentences that have meaning to compilers like values and operations. The most neutral sentences in programming are comments. Comments are some sentences that programmers use to explain to others or themselves that what does the code. You can use comments in below ways:

// This is a comment. It is not executed.// This is also a comment,// over multiple lines./* This is also a comment. Over many...
many...
many lines. */

Above snippet show you some comment that won’t any result in code and is just for explain some info to next programmers or last programmer after some times. Also comments can be nested. It means that when you use multiline Comments inside each other like below:

/* This is a comment.
/* And inside it is
another comment. */
Back to the first. */

There is another way to comment code that called documentation comments. It is used for single line via /// and for multiline between /** and */ like below:

/// I am a documentation comment
/// at your service.
/**
* Me, too!
*/

Documentation comments are useful to document code because they support markup formatting so you can add even links in comments.

Statements and expressions:

Two important words that you’ll often hear thrown about in programming language documentation are statement and expression. It’s helpful to understand the difference between the two.

Statements:

A statement is a command, something you tell the computer to do. like:

print('Hello, Dart Apprentice reader!');

Print is a code that show sentence between Quotes in output panel.

expressions:

Unlike a statement, an expression doesn’t do something; it is something. That is, an expression is a value, or is something that can be calculated as a value.

423 + 2'Hello, Dart Apprentice reader!'

The values can be numbers, text, or some other type.

Operators:

Operators are actions that can be used in expressions and are in three common types:

Arithmetic operators that are use to math operations like +(add), -(subtraction), *(multiplication), /(division)

AND

Assignment operators that are use to assigning value to variables, like =(assignment), +=(add and then assign), -=(subtract and then assign)

AND

Logical or Boolean operators that are use to check logical operations, like ==(equality), <(Less than), >(Greater than), !=(Not equal)

Order of operations:

Of course, it’s likely that when you calculate a value, you’ll want to use multiple operators. Here’s an example of how to do this in Dart:

((8000 / (5 * 10)) - 32) ~/ (29 % 5)

Note the use of parentheses, which in Dart serve two purposes: to make it clear to anyone reading the code — including yourself — what you meant, and to disambiguate the intended order of operations. For example, consider the following:

350 / 5 + 2

Does this equal 72 ( 350 divided by 5 , plus 2 ) or 50 ( 350 divided by 7 )? Those of you who paid attention in school will be screaming, “72”! And you’d be right.

In Dart like most of programming languages, order of operations is following below sequence (left to right):

()    then     %     then     /*    then    +-

There are more operators in Dart, but the book content with just these cases. For more operators and learn more detail please open below link and read Operators part:

Variables and Constants:

Variables and Constants are like dishes to hold values. For example, suppose you want to program a software that will sort Math number for 20 student and then calculate the Best and Average number of class. So you’ll need something to hold students numbers to process on them and obtain requested values.

In programming for holding values during the run, you need Variables and Constants. Their difference is obvious in names. Variables can be changed but Constants must be declared once and then they could not be changed.

In below snippet you see how different type of Variables and Constants are declared:

int age = 30;
double pi = 3.14159;
const x = 46;

In above snippet ‘age’ and ‘pi’ are two variables that hold 30 and 3.14159 amounts in themselves. After declaration you can change their values how many you want but you can not change value of ‘x’ after declaration, because it’s a Constant. It will keep its value until program stop working.

Naming data Variables Constants:

Always try to choose meaningful names for your variables and constants. Good names act as documentation and make your code easy to read. A good name specifically describes the role of a variable or constant. Here are some examples of good names: personAge, numberOfPeople, gradePointAverage

Often a bad name is simply not descriptive enough. Here are some examples of bad names: a, temp, average

Types & Operations:

In Dart, a type is a way to tell the compiler how you plan to use some data. By this point in this book, you’ve already seen the following types:

  • int
  • double
  • num
  • String
  • bool
  • dynamic

You are familiar with int and double, first to hold Integer numbers and second to hold Floating point numbers. The third one, num do both int and double task. It means that num can hold both Integer and Floating point numbers, but be careful that once you declare a variable as num and set an int or double value, you can not change it to other type. It’ll be cause runtime error.

num someNumber = 3;double someDouble = someNumber as double;

This will crash with the following message:

CastError (type 'int' is not a subtype of type 'double' in type cast)

Numbers are essential in programming, but they aren’t the only type of data you need to work with in your apps. Text is also a common data type, representing things such as people’s names, their addresses, or even the complete text of a book. All of these are examples of text that an app might have to handle. Most computer programming languages store text in a data type called a string.

String name = 'Hamed';

‘bool’ is a type that can hold just true or false. Sometimes in programming you need to hold result of a comparison, for example like below:

int myAge = 30;
int yourAge = 20;
bool areWeSameAge = (myAge == yourAge); //false

In above snippet we have two int variables and a comparison between them. The == sign is a comparison operator that checks if both side of the sign are equal or not. If they are equal, this comparison returns true, if not, it returns false. Result of the comparison will be kept in the Boolean variable that is declared. Other comparison operators are != (not equality) , > (grater than) , < (less than) and some others that can learn more about them in below link in “Equality and relational operators” part:

‘dynamic’ lets you assign any data type you like to your variable, and the compiler won’t warn you about anything.

dynamic myVariable;
myVariable = 10; // OK
myVariable = 3.14159; // OK
myVariable = 'ten'; // OK
myVariable = true; // OK

In above snippet, there is no error.

There is another way to declare variables. In that you don’t have to tell type of variable and compiler will find it’s type.

var someNumber = 10;

By declaring ‘someNumber’ as var and assign 10 value to it, compiler will use someNumber as int. below snippet tell more example:

var someDouble = 3.14159;var name = 'hamed';

But be careful that once you assign the value to a declared var, you set its type and you can not assign a value from other types. see below:

var someNumber = 10;someNumber = 15;      // OK
someNumber = 3.14159; // No, no, no.

It will cause runtime error, because when 10 is assigned to someNumber, compiler will know it as int and will cause error if programmer try to assign another types values.

Control Flow:

When writing a computer program, you need to be able to tell the computer what to do in different scenarios. For example, a calculator app would need to perform one action if the user taps the addition button, and another action if the user taps the subtraction button. In computer programming terms, this concept is known as control flow, because you can control the flow of decisions the code makes at multiple points.

There are some statements like other programming languages to control flow of code that are introduced below:

if statement:

The first and most common way of controlling the flow of a program is through the use of an if statement, which allows the program to do something only if a certain condition is true.

if (2 > 1) {
print('Yes, 2 is greater than 1.');
}

In above snippet, after ‘if’ keyword, there is a condition in parentheses. This condition checks if 2 is grater than 1, then run the code in block (between curly braces). If not, then do nothing.

else clause:

You can extend an if statement to provide code to run in the event that the condition turns out to be false . This is known as the ‘else’ clause. it means that if you use ‘else’ clause like below and then condition statement in if got false, the else part will run.

const animal = 'Fox';
if (animal == 'Cat' || animal == 'Dog') {
print('Animal is a house pet.');
} else {
print('Animal is not a house pet.');
}

and in output you will see:

Animal is not a house pet.

The || sign is another conditional operator, is called ‘logical OR’. it means that if animal is equal cat or is equal dog, the statements result is true.

Else-if chains:

You can go even further with if statements. Sometimes you want to check one condition, and then check another condition if the first condition isn’t true. This is where else-if comes into play, nesting another if statement in the else clause of a previous if statement. You can use it like so:

const trafficLight = 'yellow';
var command = '';
if (trafficLight == 'red') {
command = 'Stop';
} else if (trafficLight == 'yellow') {
command = 'Slow down';
} else if (trafficLight == 'green') {
command = 'Go';
} else {
command = 'INVALID COLOR!';
}
print(command);

and you will see in result:

Slow down

The ternary conditional operator:

There is a conditional statement in Dart like some other programming languages that can be use instead of else-if statement. it is to short and simple, like below:

(condition) ? valueIfTrue : valueIfFalse;

In above statement you don’t need if and else keywords and even curly braces. It is good for situations that you have one-line statements to run if if or else blocks. Otherwise it will be unreadable and is not useful. See below example:

const score = 83;const message = (score >= 60) ? 'You passed' : 'You failed';

It is better than below if-else statement:

const score = 83;
String message;
if (score >= 60) {
message = 'You passed';
} else {
message = 'You failed';
}

Switch statements:

An alternate way to handle control flow, especially for multiple conditions, is with a switch statement. The switch statement takes the following form:

switch (variable) {
case value1:
// code
break;
case value2:
// code
break;
...
default:
// code
}

There are a few different keywords, so here are what they mean:

  • switch : Based on the value of the variable in parentheses, which can be an int, String or compile-time constant, switch will redirect the program control to one of the case values that follow.
  • case : Each case keyword takes a value and compares that value using == to the variable after the switch keyword. You add as many case statements as there are values to check. When there’s a match Dart will run the code that follows the colon.
  • break : The break keyword tells Dart to exit the switch statement because the code in the case block is finished.
  • default : If none of the case values match the switch variable, then the code after default will be executed.

Loops:

Computer programming is just as full of repetitive actions as your life is. The way you can accomplish them are by using loops. Dart, like many programming languages, has while loops and for loops.

While loops:

A while loop repeats a block of code as long as a Boolean condition is true. You create a while loop like so:

while (condition) {
// loop code
}

Here’s a (somewhat) more useful example of a while loop:

var sum = 1;
while (sum < 10) {
sum += 4;
print(sum);
}

Run that to see the result. The loop executes as follows:

  • Before 1st iteration: sum = 1 , loop condition = true
  • After 1st iteration: sum = 5 , loop condition = true
  • After 2nd iteration: sum = 9 , loop condition = true
  • After 3rd iteration: sum = 13 , loop condition = false

After the third iteration, the sum variable is 13 , and therefore the loop condition of sum < 10 becomes false . At this point, the loop stops.

Do-while loops:

It differs from the while loop in that the condition is evaluated at the end of the loop rather than at the beginning. Thus, the body of a do-while loop is always executed at least once. You construct a do-while loop like this:

do {
// loop code
} while (condition)

Here’s the example from the while section, but using a do-while loop:

sum = 1;
do {
sum += 4;
print(sum);
} while (sum < 10);

and you will see the result:

5
9

For loops:

In addition to while loops, Dart has another type of loop called a for loop. This is probably the most common loop you’ll see, and you use it to run a block of code a set number of times. Here’s a simple example of a for loop in Dart:

for (var i = 0; i < 5; i++) {
print(i);
}

If you have some prior programming experience, this C programming language style for loop probably looks very familiar to you. If not, though, the first line would be confusing. Here’s a summary of the three parts between the parentheses and separated by semicolons:

  • var i = 0 (initialization): Before the loop starts, you create a counter variable to keep track of how many times you’ve looped. You could call the variable anything, but i is commonly used as an abbreviation for index. You then initialize it with some value; in this case, 0 .
  • i < 5 (condition): This is the condition that the for loop will check before every iteration of the loop. If it’s true , then it will run the code inside the braces. But if it’s false , then the loop will end.
  • i++ (action): The action runs at the end of every iteration, usually to update the loop index value. It’s common to increment by 1 using i++ but you could just as easily use i += 2 to increment by 2 or i — to decrement by 1.

Run the code above and you’ll see the following output:

0
1
2
3
4

For-in loops:

There’s another type of for loop that has simpler syntax; it’s called a for-in loop. It doesn’t have any sort of index or counter variable associated with it, but it makes iterating over a collection very convenient.

const myString = 'I ❤ Dart';
for (var codePoint in myString.runes) {
print(String.fromCharCode(codePoint));
}

Here’s what’s happening:

  • myString.runes is a collection of all the code points in myString .
  • The in keyword tells the for-in loop to iterate over the collection in order, and on each iteration, to assign the current code point to the codePoint variable. Since runes is a collection of integers, codePoint is inferred to be an int .
  • Inside the braces you use String.fromCharCode to convert the code point integer back into a string.
  • In terms of scope, the codePoint variable is only visible inside the scope of the for-in loop, which means it’s not available outside of the loop.

Run the code and you’ll see the following output:

ID
a
r
t

Conclusion:

Thank you for accompanying me here and read this article. It is just the end of Part one and you can keep continuing Part two by below link:

Please let me know your opinions until here and comment me your advices. Thank you waiting for the second part.

--

--