In the last article we installed Flutter & Dart and improved our setup with numerous Visual Studio Code Extensions. Now let’s take a look at the basics of Dart and learn the syntax of Dart.
Note: This series is not intended to teach you programming from scratch. You should already have an understanding of programming and now want to learn Dart & Flutter.
A simple Dart program
Now let’s look at the simplest dart program, a typical “Hello, World!” program. Every Dart program starts with a **main**
function, which is later executed first.
Great! But this doesn’t help yet, because there is nothing between the that can be executed.
With the function print
you can easily type something into the console.
As you can see, we wrote ‘ ’ inside of the brackets. These are there to represent a string. But you can also write strings with “ ” in Dart.
You can also see that there is a semicolon after the print. This is always needed after a statement in Dart. Complex statements, such as for-loops or if-queries, do not need a semicolon, but more about that later.
Very good, now we know how a Dart program is basically structured. Now let’s take a closer look at the individual topics.
Comments
You write a single line comment like this:
You can also write your comments over several lines:
Great! But there is another way to write comments, which is very useful for large comments:
Everything that is between the /*
and the */
will be commented.
However, there are not only normal Comments in Dart. There are also Documentation Comments. You can write them with ///
:
And over several lines:
Arithmetic Operations
To be able to perform calculations, we need arithmetic operations. These are, as in real mathematics, between the numbers.
- Add: +
- Subtract: -
- Multiply: *
- Divide: /
Okay, that was very simple. But Dart also offers Math functions, which can be very helpful. To do this you import the library dart:math
:
(Now you have already learned how imports work. We will discuss this in more detail later).
Now you can call some functions like this:
min
: Find the smallest value of something. Example:min(5, 10);
will be 5.max
: Find out the largest value of something. Example:max(5, 10);
will be 10.sqrt
: Gives you the square root of a number. Example:sqrt(3)
is 1.732050808.
There are other functions like sin
for sine functions or cos
for cosine functions.
There is a lot more to say about the dart:math library. To learn more about it, you can check out the document: https://api.dart.dev/stable/2.16.1/dart-math/dart-math-library.html
Conclusion
That’s it for today. You have learned how a simple dart program is built and something about comments. You also know how to use mathematical functions.
A little exercise for you: Try to combine the functions used above.
In the next article of this series, we will deal with the use of variables.
Thanks for reading, have a nice day!