Dart First Program
Learning a programming language, the best approach is not to memorize syntax rules first, but to get a program running first, and then ask what each line means.
In this chapter, we'll start from the simplest program and gradually expand to a slightly more complete small program, covering the most basic concepts of Dart in the process.
The standard file extension for Dart language is .dart, for example hello.dart.
* * *
## Simplest Program: Hello, Dart!
Open DartPad [https://dartpad.dev](https://dartpad.dev/) (or create a hello.dart file in a local editor), and enter the following code:
## Example
void main(){
print('Hello, Dart!');
}
Click run, output:
Hello, Dart!
Local environment run command:
dart hello.dart
That's just 3 lines of code. Now let's figure out every character.
* * *
## Line-by-Line Analysis
### void main() {
This is the entry function declaration of the program, and Dart programs always start executing from main().
Breaking it down:
| Part | Meaning |
| --- | --- |
| void | Return type. void means "this function does not return any value after execution" |
| main | Function name. This is the entry function name agreed upon by Dart and cannot be changed to something else |
| () | Parameter list. Here it's empty, meaning the main function does not accept any parameters |
| { | Start of function body. Pairs with the } on the last line, wrapping all the code of the function |
> main() is the only entry point of Dart. No matter how many files or classes your program has, execution always starts from the first line of main().
### print('Hello, Dart!');
This is a statement that outputs the content inside the parentheses to the console.
Breaking it down:
| Part | Meaning |
| --- | --- |
| print | Built-in function name, used to output a line of text to the console |
| (...) | Parameter list of the function call |
| 'Hello, Dart!' | A string literal, wrapped in single quotes ' |
| ; | Statement terminator. Every statement must end with a semicolon |
| Two spaces at the beginning | Indentation, indicating this line of code belongs inside the main() function. Dart convention uses 2 spaces for indentation |
### }
The end marker of the main() function body, paired with the opening {.
### Overall Structure Diagram
void main() { β Function signature (return type + function name + parameters) print('Hello, β Function body: calling print function Dart!'); β Passing string parameter, ending with ;} β End of function body
* * *
## Two Ways to Write Strings
In Dart, strings can be wrapped in single quotes or double quotes, and they are completely equivalent.
## Example
void main(){
print('Hello, Dart!');// Single quotes
print("Hello, Dart!");// Double quotes, same effect
}
Hello, Dart!Hello, Dart!
When to use which quote? You can refer to the following scenarios:
| Scenario | Recommended | Example |
| --- | --- | --- |
| General case | Single quotes (Dart community convention) | 'Hello' |
| String contains single quotes | Double quotes | "It's a beautiful day!" |
| String contains double quotes | Single quotes | 'He said:"Hello"' |
> When the string content itself contains single quotes, using double quotes is more convenient, saving the need for escaping. The Dart community convention is to prefer single quotes, and this tutorial will also use single quotes primarily.
* * *
## Comments
Comments are explanatory text written for people, and the Dart compiler will completely ignore them.
## Example
void main(){
// This is a single-line comment, from // to the end of the line
print('Hello, Dart!');// Can also be written after a statement
/*
This is a multi-line comment.
Can span multiple lines,
often used to temporarily comment out a large block of code.
*/
/// This is a documentation comment, used to describe the purpose of functions, classes, or variables.
/// IDEs will display documentation comments as hover tooltips.
}
| Comment Type | Syntax | Usage |
| --- | --- | --- |
| Single-line comment | // content | Explain a particular line of code |
| Multi-line comment | /* content */ | Comment out a block of code, or write longer explanations |
| Documentation comment | /// content | Describe APIs, used for generating documentation |
> Good comments explain "why", not "what". The code itself already explains "what" it does; comments should supplement the reasoning or intent behind it.
* * *
## Variables: Giving Names to Data
A program cannot only output fixed text; we need variables to store and use data.
## Example
void main(){
String name ='TUTORIAL';
int age =25;
double height =1.68;
bool isStudent =true;
print(name);
print(age);
print(height);
print(isStudent);
}
TUTORIAL 251.68true
### Variable Declaration Format
Type name variable name = initial value ; β β β ββ Statement terminator β β ββ Assignment operator β ββ The name you give to this data ββ Tell Dart what type of data this variable stores
### Quick Overview of Basic Data Types
| Type | Description | Example |
| --- | --- | --- |
| String | Text string | 'TUTORIAL', "hello" |
| int | Integer | 25, -10, 0 |
| double | Decimal (floating point) | 1.68, 3.14 |
| bool | Boolean (true/false) | true, false |
The detailed content of data types will be covered in later chapters; here we'll just get a preliminary impression.
* * *
## Using var for Automatic Type Inference
Writing the type name every time is a bit tedious.
Dart supports using the var keyword for automatic type inferenceβthe compiler will determine the type based on the value you assign.
## Example
void main(){
var name ='TUTORIAL';// Inferred as String
var age =25;// Inferred as int
var height =1.68;// Inferred as double
var isStudent =true;// Inferred as bool
print(name);
print(age);
}
TUTORIAL 25
The type inferred by var is determined at compile time and cannot be assigned to a different type later.
## Example
void main(){
var name ='TUTORIAL';
name ='Bob';// Allowed, still String
// name = 123; // Error: cannot assign int to a String variable
}
When to use var, and when to explicitly write the type?
| Scenario | Recommended | Reason |
| --- | --- | --- |
| Local variable, type is obvious at a glance | var | More concise |
| Function parameters, class fields, return types | Write explicit type | Clearer code, self-documenting |
* * *
## String Interpolation: Embedding Variables in Strings
If you want to embed a variable's value into a string, Dart provides a very concise string interpolation syntaxβusing $variableName or ${expression}.
## Example
void main(){
var name ='TUTORIAL';
var age =25;
print('My name is $nameοΌThis year $age Ageγ');
print('Next year I will be ${age + 1} Ageγ');
}
My name is TUTORIALοΌThis year 25 AgeγNext year I will be 26 Ageγ
| Syntax | Usage | Example |
| --- | --- | --- |
| $variableName | Directly embed variable value, concise | $name |
| ${expression} | Embed any expression (calculation, method call, etc.) | ${age + 1}, ${name.toUpperCase()} |
> Compared to print('My name is ' + name + 'οΌThis year ' + age.toString() + ' Ageγ') string concatenation, interpolation syntax is clearer and safer, and is the idiomatic Dart style.
* * *
## A Slightly More Complete Program
Now let's combine everything we've learned so far and write a somewhat more realistic program: a simple self-introduction generator.
## Example
void main(){
// Personal information
var name ='TUTORIAL';
var age =25;
var city ='Shanghai';
var
YouTip