+5 votes
221 views
in Web development by (242k points)
reopened
Dart tutorial: practical first steps

1 Answer

+3 votes
by (1.6m points)
edited
 
Best answer

Dart's origins
First steps to learn Dart
Dart in practice
Dart operators overview
Define and use variables
Character string in Dart tutorial
Juggling figures with Dart
Set conditional statements
One more and one less also with Dart
Spin in Dart: Loops

image

Dart tutorial: practical first steps

The Dart programming language is young, but it has already established itself, especially in the field of mobile application programming. Google has created Flutter , a software development kit (SDK) that uses Dart, thus promoting the use and dissemination of this programming language. An important advantage is that with it you can program applications for all mobile operating systems : Apple iOS, Google Android or Microsoft Windows Phone..

Learn the Dart language! Our Dart tutorial guides you through your first steps into the world of Google's programming language. You will see that it is not that difficult. For more information on the language itself, see our article What is Dart ?, with detailed information about it, and the article on Flutter to find out more about Google's Software Development Kit.

Index
  1. Dart's origins
  2. First steps to learn Dart
  3. Dart in practice
    1. Define and use variables
    2. Character string in Dart tutorial
    3. Juggling figures with Dart
    4. Set conditional statements
    5. One more and one less also with Dart
    6. Spin in Dart: Loops
  4. Dart operators overview

Dart's origins

Dart was originally introduced to address shortcomings in JavaScript that, from the developers' point of view, could no longer be improved within the programming language itself. In this way, they began to look for a way to simplify or bring together certain internal logics without having to renounce the range of possibilities of language. As an example, the JavaScript code would be as shown below:

  getElementsById() getElementsByTagName() getElementsByName() getElementsByClassName() querySelector() querySelectorAll() document.links document.images document.forms document.scripts formElement.elements selectElement.options  

Instead, in code in Dart it would be like this:

  elem.query('#foo'); elem.queryAll('.foo');  

First steps to learn Dart

A programming language is made up of a great variety of? Vocabulary? with which data are structured and operations (algorithms) are developed. To do this, the language uses a certain number of concepts: variables , which only have one purpose. Some examples in Dart are? Var ?,? Int? ? if ?,? else? or? while ?. In our article on Internet programming languages, you will discover more about the architecture of programming languages. By combining variables, operators, conditionals, functions and many other elements, the sequence of the program is born at the end of which a result is obtained..

Dart in practice

We present you the first examples, simple and easy to understand, to learn Dart. You can modify them to your liking and experiment with them. All programming routines begin with the call to the main function. As an example, we take the classic code? Hello world ?:

  void main () { print("Hola, mundo"); }  

In front of the function? Main ?, is the function without return type? Void ?, which does not return any value. The parentheses ? ()? indicate a function , and inside braces ? {? }? Dart code runs (in this example the command is to print something to the screen). Behind the slashes ? //? there is a comment that remains invisible; also represented with? / * this is a multi-line comment ... * /? (known example in PHP). In this way, you can comment on your own code or that of other developers in a structured way, which greatly facilitates teamwork on existing projects.

Note

As in Java, C, or PHP, all statements in Dart are closed with a semicolon..

Go ahead and try the following examples using the free open source DartPad platform. One of the advantages of this tool is that it numbers the lines of the program and indicates if there are errors. Also, some programming examples are available in a drop-down menu.

The following code examples no longer include? Void main () {?} ?.

Define and use variables

With the variables, the spaces of the program are determined. We start with the numbers.

  var mySize = 174;  

Here a new variable has been determined ? My space? which has been assigned the value ? 174 ?. This variable maintains this value in the programming sequence until it is actively modified by operators or functions. To obtain the value of the variables, we use the command? print ?.

  var mySize = 174; print(mySize); int yourSize = 174; print(yourSize); double thisSize = 1.74; print(thisSize); dynamic oneSize = 'Onehundredseventyfor' + ': ' + '174'; print(oneSize);  

With the command? Print? On DartPad, you get the following results from lines 3, 6, 9, and 12 on the console:

image
For the variables you can choose (almost) any denomination, which facilitates the reading and correction of the program code.

The variables in Dart support certain types , which can be integers (? Int?) Or decimal numbers (? Double?). The type of variable? Dynamic? it can support different values ​​and expressions in the programming sequence. In contrast, blank lines, tabs, and paragraphs are not taken into account during the execution of the routine. Therefore, the values ​​are located directly below each other on the right in the console.

When trying to assign a wrong value to a certain type of variable, an error message with the corresponding description is generated in DartPad:

  int mySize = 1.74; // integer is expected, but double comes print(mySize);  
image
With? 1issue (s) ?, DartPad reports a wrongly assigned value. In the example, a decimal value cannot be assigned to an integer variable. The error occurs on line 2 of the programming sequence, and the wrong value is underlined in orange.
Note

The designations (identifiers) for the variables used cannot contain reserved words. Neither are figures at the beginning or blank or special characters allowed, with the exception of the underscore? _? and the dollar symbol? $ ?. Identifiers are case-sensitive and must be unique.

Character string in Dart tutorial

By character strings , with the data type? String ? (beware: with a capital S), different characters can be processed in the Dart language. Here we show you how to program multiple lines 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);  
image
Text in one or more lines in Dart depending on the number of quotes used.

Using the String function, the text is reproduced by enclosing the desired content in single or double quotation marks: 'or ". But if the text is opened and closed with three times either of the two types of quotation marks (' '' or" "" ), Dart prints the text with line breaks at the position where they are inserted. In this way, it is possible to format the result.

advice

Smart quotes (usually English quotes) can be easily inserted into text in Windows with the key combination [Alt] + 0147 (opening quote) and [Alt] + 0148 (closing quote), and appear well in a dart chain. On macOS , quotation marks are inserted with [Alt] + [Shift] + [W] and [Alt] + [2].

Juggling figures with Dart

There is not a big difference between the declaration of variables and the calculations of variables in which both figures and expressions can be added. To calculate results, Dart uses arithmetic operators . For example, a task could be for the customer to select an item from an online store of which they want to purchase three units . In the cart function, the unit price would have to be multiplied by? 3 ?, and once the calculation is done, show the total price. In the following code you can see the use of different methods for the dataset, in addition to the comments on 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);  
image
Example of a simple calculation in combination with text fragments.

In this image we visualize strings, integer and decimal values, and the set of programming elements for new variables . Special care must be taken when combining two existing variables into a new variable to ensure we get the correct result on the screen. In this case, for example, a dollar symbol is prepended ? $? to the variables already defined (lines 8 and 9 in the upper image of the DartPad).

Set conditional statements

Conditional statements play an essential role in programming. Here we show you how to program a conditional with Dart. A conditional always leads to a decision in this sense: if A ( if ) occurs, X appears on the screen; if case B ( elseif ) occurs, then Y is displayed; if neither case ( else ) occurs , then the result is Z. With the Dart commands in parentheses, the following code is obtained:

  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.'); } }  

This is how it looks on DartPad:

image
Conditional statements force planned results onto the screen.

If you want to learn more about the Dart language, substitute DartPad for the word? Glove? by? tweezers ?,? ruler? or? brush? and observe the changes of the output programmed in the console. You can modify it to your liking and apply it to different cases. Here the operator appears for the first time ? ||? which represents the logical name? or ?. In Dart it cannot be applied with? OR ?.

One more and one less also with Dart

To program the next section, we have to learn the so-called increment and decrement functions in Dart, which gradually add and subtract a result. In the example, the value 50 is modified with the operators? ++? Y ???.

  var upAndDown = 50; print (upAndDown); print('----'); ++upAndDown; print (upAndDown); print('----'); upAndDown++; print (upAndDown); print('----'); --upAndDown; print (upAndDown); print('----'); upAndDown--; print (upAndDown);  
image
The value 50 is gradually increased and decreased.

Here we see that it is possible to obtain as a result a simple string of characters without previous definition by adding it between parentheses with quotation marks using the? Print? in the program code. This only serves for the optical structuring of the result. With this knowledge, you are ready to program loops.

Spin in Dart: Loops

Loops are also an important part of day-to-day programming. We refer, for example, to comparisons with existing spaces . To do this, you have to use the following? Expression ?: we have the value A that is continuously modified until reaching the space (state) B. This is represented in the Dart code:

  String myLabel = ' pieces'; var piece = 3; while (piece < 12) { var allThisStuff = '$piece $myLabel'; print(allThisStuff); piece++; }  

What does DartPad do with this?

image
The loops run repeatedly until a defined conditional is met.

In this example, conditional statements could also be included again if, for example, words in the singular or plural are differentiated:

  int amount = 1; var itemSing = 'blouse'; var itemPlural = 'blouses'; if (amount == 1) { print(itemSing); } else { print(itemPlural); }  

To learn Dart, copy this code sample into DartPad and modify the integer variable? Amount? for the article to be printed? blouse? singular or plural.

Dart operators overview

You just learned some operators to program with Dart. In the following table, you will find a summary of the most important operators.

In the table, the value 35 has been applied to the variable? Muster ?.

  var muster = 35;  
Operator type Denomination Symbol Example Outcome        
Arithmetic Sum + var muster + 2; 37        
  Subtraction - var muster - 2; 33        
  Multiplication * var muster * 3; 105        
  Division / var muster / 7; 5        
  Divide and return an integer result ~ / var muster ~ / 7; eleven        
  Assign sum + = var muster + = 6; 41        
  Assign subtraction - = var muster - = 7; 28        
  Assign product * = var muster * = 2; 70        
  Assign division / = var muster / = 7; 5        
                 
Of equality and relational It does not matter == var muster == 35; True        
  It is not the same ! = var muster! = 44; True        
  Smaller than < var muster <44; true        
  Less than or equal to <= var muster <= 33;          
  Greater than > 44> var muster; True        
  Greater than or equal > = var muster> = 23;          
                 
Increase and decrease Increases ++ ++ var muster; 36        
  Increases ++ var muster ++; 36        
  Decreases - --var muster; 3. 4        
  Decreases - var muster--; 3. 4        
  Remaining value % % var muster% 3; 2        
                 
Logical Y && muster1 && muster2 ? and        
  or       muster1   muster2 ? or
  Denial ! muster1! muster2 ? not        
                 
Conditionals If-else ? ? : var y = muster <34? 15:10; 10        
  If-else ? ? : var y = muster <36? 15:10; fifteen        
  Check if it is Null ?? var y = muster ?? 9; 35        
  Check if it is Null ?? var z = 0 ?? muster; 35        

With these basic knowledge, you can now dive into programming with Dart and you will be one step closer to programming your own application.


...