DART Tutorial
The young programming language DART has already gained a foothold, especially when it comes to programming mobile apps. With Flutter, Google has set up a software development kit (SDK) that uses DART, promoting the usage and distribution of this programming language. A significant advantage is that it can be used to program apps for all mobile operating systems, meaning Apple iOS, Google Android, and Microsoft Windows Phone.
This DART tutorial introduces you to the world of Google’s programming language – one that’s comparably easy to master. Our article “What is DART?” provides more information on the language itself. You can also find out more in our article on Google’s software development kit Flutter.
The origin of DART
DART originally came about to overcome JavaScript vulnerabilities that, from a developer’s perspective, could no longer be processed within this established programming language.
In doing so, DART became a way to simplify or summarize certain internal types of logic without losing sight of the possibilities. To give an example: JavaScript has:
getElementsById()
getElementsByTagName()
getElementsByName()
getElementsByClassName()
querySelector()
querySelectorAll()
document.links
document.images
document.forms
document.scripts
formElement.elements
selectElement.options
What remains in DART is:
elem.query('#foo');
elem.queryAll('.foo');
Getting started with DART
A programming language consists of a world of “vocabulary” with which data is structured and processes (algorithms) are designed. To do so, the language uses a defined number of terms: variables that must not be used for other purposes. Some examples in DART are “var”, “int”, “if”, “else”, or “while”. You can find more details on the architecture of programming languages in our guide on internet programming languages. The combination of variables, operators, conditions, functions, and much more creates the program flow, at the end of which a result is output.
DART made simple
Below, we’ve rounded up some simple examples for learning DART programming, which you can then expand on or experiment with. Each program routine starts with calling up the main function, for example:
void main () {
print("Hello World!");
}
In front of the “main” function is the “void” return type, which does not return anything. The parentheses “()” indicate a function, and, within the curly brackets “{…}”, the DART code is executed. Here, the command is to output something on the screen. Behind two slashes “//” is a comment that remains invisible. This also works with “/* this is a multi-line comment ...*/”, which is a known example from PHP. This allows you to make a structured comment on your own code for yourself or for other developers, which makes team work on existing projects much easier.
Just like with Java, C, or PHP, all DART statements must be terminated with a semicolon.
You can easily try out the following examples for yourself with the free, open-source platform DartPad. One of the advantages of this pad is that it numbers the lines of the program and outputs error messages if necessary. In addition, some programming examples are available from a drop-down menu.
“Void main() {...}” is no longer included in the other code examples in this text.
Defining and using variables
Fixed scales for the program are defined with variables. We’ll start with numbers.
var mySize = 174;
This defines a new variable: “mySize”. It has been assigned the value “174”. This variable remains with its value in the program flow until it is actively changed by operators or functions. The command “print” comes into play to output the value of the variable.
var mySize = 174;
print(mySize);
int yourSize = 174;
print(yourSize);
double thisSize = 1.74;
print(thisSize);
dynamic oneSize = 'Onehundredandseventyfour' + ': ' + '174';
print(oneSize);
In DartPad, this results in the following output from lines 3, 6, 9, and 12 in the console using the “print” command:
The variables in DART take certain types. These can be integers (“int”) or floating-point numbers (“double”). The variable type “dynamic” can have different values and expressions in the program flow. In contrast, blank lines, tabs, and paragraphs are not taken into account when executing the routine. For this reason, the values to the right in the console are directly below one another.
Attempting to assign an incorrect value to a certain variable type generates an error message with an error description in DartPad:
int mySize = 1.74; // integer is expected, but double comes
print(mySize);
The names (identifiers) for the variables used may not contain any keywords. Numbers at the beginning, as well as spaces and special characters, are not permitted, except for the underscore “_” and the dollar sign “$”. Identifiers are case sensitive and must be unique.
Character strings in the DART tutorial
With character strings, the data type “String” (Attention: with a capital S at the beginning), any character can be processed in DART programming. In this context, you will also learn how to program multi-line, formatted rows in DART.
String text1 = 'this is a single line string';
String text2 = '''this is a multiline
line string with a break''';
print(text1);
print(text2);
Text is displayed as a string by enclosing the desired content with single or normal quotation marks: ' or ". However, if the text is started and ended with triple quotation marks (''' or """), DART also outputs the text as a break at the point where it is wrapped. This provides a way to format the output.
Typographic quotation marks (mostly in the correct English version) can easily be placed in the text in Windows by using the key combinations [Alt] + 0147 (opening quotation marks) and [Alt] + 0148 (closing quotation marks). They are also output as such in a string by DART. In macOS, you can add these quotation marks with [Alt] + [Shift] + [W] and [Alt] + [2].
Number acrobatics with DART
It is a short way from the definition of variables to calculations with variables. Numbers and even expressions can be added together. DART uses arithmetic operators to calculate results. For example, one task could be that an item was selected in an online shop, and the customer would like to buy three of those items. So in the shopping cart function, the unit price must be multiplied by “3”, and the total price must be shown at the end of the calculation. The following code shows how different methods of merging data are used, along with comments in the relevant lines:
String product = 'calendar';
String curr = 'EUR';
String isFor = 'for'; // 3 strings for later print use
double singlePrice = 7.96; // floating comma for single price
int amount = 3; // number of ordered calendars
var totalPrice = (amount*singlePrice); // calculation of the total price with multiplier *
var invTotal = '$totalPrice $curr'; /* Merging of two variables in a new one by adding a $ sign before the old variables.*/
var result = '$amount $product\s'; //also plus adding a letter “s” for plural
print (invTotal); // creating the screen output
print (isFor);
print (result);
There are strings, floating-point, and integer numbers, as well as the merging of programming elements into new variables. A special feature should be noted when merging two existing variables into a new variable for output on the screen: In this case, the variables that have already been defined are preceded by a dollar sign “$” (lines 8 and 9 in the above DartPad illustration).
Setting conditions
When programming, conditions play an important role. Here you will learn how to program a condition with DART. A condition always leads to a decision, in the sense of: If (if) case A occurs, display X appears on the screen; if case B occurs (elseif), then display Y appears; if neither applies (else), display Z is output. The following code results with the DART commands shown in brackets:
var tOol = 'Glove';
if (tOol == 'Pliers' || tOol == 'Ruler')
{ print('That is a tool.');
} else if (tOol == 'brush')
{ print('That is a tool.');
} else { print('That is not a tool.');
}
}
In DartPad, it looks like this:
Expand your own knowledge in the DART tutorial and change the word “glove” to “pliers”, “ruler”, or “brush” in DartPad to observe the changes in the programmed output on the console. This can be expanded on as required and applied to various cases. The operator “||” now appears for the first time. These double lines stand for the logical term “or”, which cannot be used in DART as the word “OR”.
Up and down is also possible with DART
To program the following section, we have to learn the so-called increments and decrements in DART. These control the gradual increase or decrease of an output value. In the example, the number 50 is changed with the operators “++” and “—”.
var upAndDown = 50;
print (upAndDown);
print('----');
++upAndDown;
print (upAndDown);
print('----');
upAndDown++;
print (upAndDown);
print('----');
--upAndDown;
print (upAndDown);
print('----');
upAndDown--;
print (upAndDown);
Here, you can also see that a simple character string can be output without prior definition by placing it between parentheses with quotation marks using “print” in the program code. This is only used for the visual structuring of the result. With this knowledge, you can now program loops.
Going in circles: loops in DART
Loops are also important program routines that are required again and again, like for making comparisons with existing sizes, for example. To do this, the following “wording” is used: We have value A; keep changing this value until size (condition) B is reached. As DART code, it looks like this:
String myLabel = ' pieces';
var piece = 3;
while (piece < 12) {
var allThisStuff = '$piece $myLabel';
print(allThisStuff);
piece++;
}
What does DartPad do with it?
In this example, conditions could also be used again if, for example, words differ in their singular and plural forms:
int amount = 1;
var itemSing = 'blouse';
var itemPlural = 'blouses';
if (amount == 1)
{ print(itemSing);
} else { print(itemPlural);
}
To learn how to program with DART, copy this code example into DartPad and change the integer variable “quantity” so that the article “blouse” is output in the singular or plural form.
DART operators at a glance
You have now learned some operators to use for programming in DART. The following table gives you an overview of the most important operators available.
In the table, the variable “example” is assigned a value of 35.
var example = 35;
Operator type | Name | Symbol | Example | Output | ||||
---|---|---|---|---|---|---|---|---|
Calculate | Addition | + | var example + 2; | 37 | ||||
Subtraction | - | var example - 2; | 33 | |||||
Multiplication | * | var example * 3; | 105 | |||||
Division | / | var example / 7; | 5 | |||||
Integer division | ~/ | var example ~/7; | 11 | |||||
Increase by | += | var example += 6; | 41 | |||||
Decrease by | -= | var example -= 7; | 28 | |||||
Multiply by | *= | var example *= 2; | 70 | |||||
Divide by | /= | var example /= 7; | 5 | |||||
Compare | Identical | == | var example == 35; | True | ||||
Not identical | != | var example ! = 44; | True | |||||
Less than | < | var example < 44; | True | |||||
Less or equal to | <= | var example <= 33; | False | |||||
Greater than | > | 44 > var example; | True | |||||
Greater or equal to | >= | var example>=23; | False | |||||
Change | Ascending | ++ | ++var example; | 36 | ||||
Ascending | ++ | var example++; | 36 | |||||
Descending | -- | --var example; | 34 | |||||
Descending | -- | var example--; | 34 | |||||
Residual value | % | %var example%3; | 2 | |||||
Logic | AND | && | example1 && example2 | … and | ||||
OR | example1 | example2 | … or | |||||
Negation | ! | example1 ! example2 | … is not | |||||
Conditions | If-Then | ? … : | var y = example < 34 ? 15 : 10; | 10 | ||||
If-Then | ? … : | var y = example < 36 ? 15 : 10; | 15 | |||||
Check for zero | ? | var y = example ?? 9; | 35 | |||||
Check for zero | ? | var z = 0 ?? example; | 35 |
With this basic knowledge, you can now take further steps in DART, and your goal of programming your own app isn’t that far off anymore!