20
Basics of Dart
In this post, I will be going over the very basics of Dart. I will be covering things that are both unique to Dart (in some ways) and standard things that every programming language has. Let's get started!
To start things off, let's take a look at a simple hello world example as a classic introduction to any programming language :)
// 1
void main() {
// 2
print('Hello, World!');
}
- Every dart program has to have a main function. This is your entry point that acts as the main "engine" to trigger any other logic your program may have. This snippet looks simple but it can get more complex and you can call functions or classes and combine them. You will learn more about that in the future.
- To ouput something in Dart, you use the print function. You write what you want inside the ''. In-depth coverage of functions and how it works will be covered in the future. Do note that every statement needs a semi-colon at the end of the line. Speaking of statement...
- An expression is something that has a runtime (meaning when the program has executed) value.
- A statement is basically something that tells the program to do something.
- A statement can contain expressions, but not vice-versa.
// some examples of expressions
1 + 1
// some examples of statements
var a = 1;
print('Hello, World!');
The next important concept that every programming language has is variables. A variable is just something that you want to store in memory for usage later.
String firstVar = 'first variable';
print(firstVar);
- A variable consists of a declaration and initialization. Everything to the left of the = is the declaration and to the right is the initialization.
- Breaking down this syntax, we start with the type of the variable, the name of the variable, the assignment operator, and then a value.
- Notice that there's no '' in the print function. Printing with the '' would output the literal text instead of the value of the variable.
- Do note I will cover operators and types more in the future.
- Some rules when it comes to naming variables:
- Cannot be keywords. Can find list of keywords here: https://dart.dev/guides/language/language-tour#keywords
- Can contain alphabets and numbers, but cannot have a number in the beginning.
- Cannot contain spaces or special characters except $ and _.
- I suggest not getting into habit of starting a variable name with $ or _. The reason will make more sense later.
- Prefer using camel casing for long variable names.
Another important feature in every programming langugage (or at least from the ones I know) is comments.
// this is a single line-comment
/*
* this is a multi-line comment
*/
- Dart suports both single-line and multi-line comments. Use whichever is appropriate for the situation.
That's a wrap for this intro to Dart. Next up is Dart Types!
If you have any question, leave a comment or reach out to me directly and I'll do my best to help you and / or revise my post for better clarity.
20