The First Dart Program
The best way to learn a programming language is not to memorize syntax rules first, but to get a program running, then ask line by line what each part means.
In this chapter we will start from the simplest program and gradually expand it into a slightly more complete small program, going over the most basic concepts of Dart along the way.
The standard file extension for the Dart language is .dart, for example hello.dart.
The simplest program: Hello, Dart!
Open DartPad https://dartpad.dev(or create a hello.dart file in a local editor), enter the following code:
Example
void
main
(
)
{
(
'Hello, Dart!'
)
;
}
Click Run, output:
Hello, Dart!
Local environment run command:
dart hello.dart
Just these 3 lines of code. Now let us figure out every single character.
Line-by-line analysis
void main() {
This is the program's entry function declaration; a Dart program always starts executing from main().
Broken down:
| Section | Meaning |
|---|---|
| void | Return type. void means this function returns no value after execution |
| main | Function name. This is the entry function name by Dart convention and cannot be changed |
| () | Parameter list. It is empty here, meaning the main function accepts no arguments |
| { | Start of the function body. Pairs with the } on the last line, wrapping all the code of the function |
main() is Dart's only entry point. 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 whose role is to output the contents inside the parentheses to the console.
Broken down:
| Section | Meaning |
|---|---|
| A built-in function name, used to output a line of text to the console | |
| (...) | The argument list of the function call |
| 'Hello, Dart!' | A string literal, wrapped in single quotes ' |
| ; | Statement terminator. Every statement must end with a semicolon |
| The two spaces at the front | Indentation indicates this line belongs inside the main() function. Dart convention uses 2-space indentation |
}
The end marker of the main() function body, paired with the opening {.
Overall structure diagram
void main() { ← 函数签名(返回类型 + 函数名 + 参数)
print('Hello, ← 函数体:调用 print 函数
Dart!'); ← 传入字符串参数,以 ; 结尾
} ← 函数体结束
Two ways to write strings
In Dart, strings can be wrapped in single quotes or double quotes; the two are completely equivalent.
Example
void
main
(
)
{
(
'Hello, Dart!'
)
;
// Single quotes
(
"Hello, Dart!"
)
;
// Double quotes, same effect
}
Hello, Dart!
Hello, Dart!
When to use which kind of quote? You can refer to the following scenarios:
| Scenario | Recommend | Example |
|---|---|---|
| General case | Single quotes (Dart community convention) | 'Hello' |
| The string contains single quotes | Double quote | "It's a beautiful day!" |
| The string contains double quotes | Single quote | 'He said: "Hello"' |
When the string content itself contains single quotes, wrapping it in double quotes is more convenient and avoids escaping. The Dart community convention prefers single quotes, and this tutorial will mainly use single quotes from here on.
Notes
Comments are explanatory text written for humans; the Dart compiler completely ignores them.
Example
void
main
(
)
{
// This is a single-line comment, from // to the end of the line
(
'Hello, Dart!'
)
;
// It can also be written after a statement
/*
This is a multi-line comment.
It 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 a function, class, or variable.
/// The IDE displays documentation comments as hover hints.
}
| Comment types | Syntax | Purpose |
|---|---|---|
| Single-line comment | // content | Explain a line of code |
| Multi-line comment | /* content */ | Comment out a block of code, or write a longer explanation |
| Documentation comment | /// content | Describe APIs, used to generate documentation |
Good comments explain why, not what. The code itself already says what; comments should add the reason or intent behind it.
Variables: giving data a name
A program cannot only output fixed text; we need variables to store and use data.
Example
void
main
(
)
{
String name
=
'RUNOOB'
;
int
age
=
25
;
double
height
=
1.68
;
bool
isStudent
=
true
;
(
name
)
;
(
age
)
;
(
height
)
;
(
isStudent
)
;
}
RUNOOB
25
1.68
true
The format of variable declaration
类型名 变量名 = 初始值 ;
│ │ │ └─ 语句结束符
│ │ └─ 赋值运算符
│ └─ 你给这个数据起的名字
└─ 告诉 Dart 这个变量存储什么类型的数据
A quick look at basic data types
| Type | Description | Example |
|---|---|---|
| String | Text string | 'RUNOOB', "hello" |
| int | Integers | 25. -10. 0 |
| double | Decimal number (floating point) | 1.68. 3.14 |
| bool | Boolean (true/false) | true, false |
The details of data types will be covered in later chapters; here just get a first impression.
Use var to infer types automatically
Writing the type name every time is a bit tedious.
Dart supports using the var keyword to automatically infer variable types -- the compiler determines the type based on the value you assign.
Example
void
main
(
)
{
var
name
=
'RUNOOB'
;
// Inferred as String
var
age
=
25
;
// Inferred as int
var
height
=
1.68
;
// Inferred as double
var
isStudent
=
true
;
// Inferred as bool
(
name
)
;
(
age
)
;
}
RUNOOB
25
The type inferred by var is fixed at compile time and cannot later be assigned a different type.
Example
void
main
(
)
{
var
name
=
'RUNOOB'
;
name
=
'Bob'
;
// OK, still String
// name = 123; // Error: cannot assign an int to a variable of type String
}
When to use var and when to write the type explicitly?
| Scenario | Recommend | Reason |
|---|---|---|
| Local variables where the type is obvious at a glance | var | More concise |
| Function parameters, class fields, and return types | Write the type explicitly | Clearer code, self-documenting |
String interpolation: embedding variables into strings
If you want to embed a variable's value into a string, Dart provides very concise string interpolation syntax -- use $variableName or ${expression}.
Example
void
main
(
)
{
var
name
=
'RUNOOB'
;
var
age
=
25
;
(
'My name is $name, I am $age years old.'
)
;
(
'Next year I will be ${age + 1} years old.'
)
;
}
我叫 RUNOOB,今年 25 岁。
明年我将 26 岁。
| Syntax | Purpose | Example |
|---|---|---|
| $variableName | Directly embeds the variable value, concise | $name |
| ${expression} | Embeds any expression (computation, method calls, etc.) | ${age + 1}, ${name.toUpperCase()} |
Compared to the string-concatenation style of print('My name is ' + name + ', ' + age.toString() + ' years old.'), interpolation syntax is clearer and safer, and is the idiomatic Dart style.
A slightly more complete small program
Now let us combine what we have learned and write a slightly more realistic program: a simple self-introduction generator.
Example
void
main
(
)
{
// Personal info
var
name
=
'RUNOOB'
;
var
age
=
25
;
var
city
=
'Shanghai'
;
var
isStudent
=
false
;
var
hobby
=
'Dart Programming'
;
// Generate the intro: the ternary operator determines identity
var
occupation
=
isStudent
?
'Student'
:
'Working professional'
;
(
'============================='
)
;
(
' Profile'
)
;
(
'============================='
)
;
(
'Name: $name'
)
;
(
'Age: $age years old'
)
;
(
'City: $city'
)
;
(
'Identity: $occupation'
)
;
(
'Hobby: $hobby'
)
;
(
'-----------------------------'
)
;
(
'Hello everyone, I am $name from $city,'
)
;
(
'I am $age years old, and I am a $occupation.'
)
;
(
'My hobby is ${hobby}, nice to meet you all!'
)
;
(
'============================='
)
;
}
=============================
个人简介
=============================
姓名:RUNOOB
年龄:25 岁
城市:上海
身份:职场人
爱好:Dart 编程
-----------------------------
大家好,我是来自上海的RUNOOB,
今年 25 岁,是一名职场人。
我的爱好是Dart 编程,很高兴认识大家!
=============================
New syntax: the ternary operator
Example
var
occupation
=
isStudent
?
'Student'
:
'Working professional'
;
This is Dart's ternary operator, with the format:
条件 ? 条件为真时的值 : 条件为假时的值
Equivalent to the following if/else form:
Example
String occupation
;
if
(
isStudent
)
{
occupation
=
'Student'
;
}
else
{
occupation
=
'Working professional'
;
}
The ternary operator is very concise when there are only two possible values; a later chapter will cover the full usage of if/else in detail.
Code style: Dart writing conventions
Good code style makes code more readable and professional.
Dart has a set of officially recommended conventions; mastering the following points is enough for beginners.
Use 2 spaces for indentation
Example
// Correct: 2 spaces
void
main
(
)
{
(
'Hello'
)
;
}
// Not recommended: 4 spaces (common in other languages, but the Dart community prefers 2)
Use lowerCamelCase for variable and function names
Example
var
firstName
=
'RUNOOB'
;
// lowerCamelCase: correct
// var first_name = 'RUNOOB'; // underscore style: not Dart convention
// var FirstName = 'RUNOOB'; // UpperCamelCase: reserved for class names
Use UpperCamelCase for class names
Example
class
UserProfile
{
}
// Correct
// class user_profile { } // Error
// class userProfile { } // Error
Use lowerCamelCase for constants (not all uppercase)
Example
const
maxRetries
=
3
;
// Dart convention: correct
// const MAX_RETRIES = 3; // This is C/Java style, not recommended in Dart
Use dart format for automatic formatting
No need to memorize the rules, just run in the project directory:
$ dart format .
The official Dart formatter automatically adjusts code to the standard style, and VS Code can also be configured to format on save.
Common errors and explanations
Beginners often encounter the following errors when writing their first program; let us get to know them.
Error 1: forgetting the semicolon
Example
void
main
(
)
{
(
'Hello, Dart!'
)
// missing ;
}
Error message:
Error: Expected ';' after this.
Solution: add ; at the end of the statement.
Error 2: mismatched parentheses
Example
void
main
(
)
{
(
'Hello, Dart!'
// missing closing parenthesis )
}
Error message:
Error: Expected ')' before this.
Solution: carefully check that every ( has a matching ). VS Code highlights mismatched parentheses.
Error 3: mismatched string quotes
void main() {
print('Hello, Dart!"); // 一个单引号、一个双引号
}
Error message:
Error: Unterminated string literal.
Solution: make sure both ends of the string use the same kind of quote.
Error 4: misspelling main
Example
void
Main
(
)
{
// M is capitalized
(
'Hello, Dart!'
)
;
}
Dart is case-sensitive; Main and main are completely different names.
The program compiles, but reports an error at runtime:
Error: No 'main' method found.
Solution: the entry function must be lowercase main.
Error 5: variable used before being assigned
Example
void
main
(
)
{
String name
;
(
name
)
;
// name is not initialized
}
The error from Dart's null safety mechanism:
Error: Non-nullable variable 'name' must be assigned before it can be used.
Solution: assign an initial value when declaring the variable, or declare it as the nullable type String? name (covered in detail in a later chapter).