Dart Basic Syntax
Every programming language has its own set of basic rules, and Dart is no exception.
This chapter introduces the basic structure of Dart programs, comment syntax, the difference between statements and expressions, and identifier naming conventions.
Program Structure and the main() Function
The Dart file name suffix is.dart..., every Dart program must have an entry point — the main() function.
The program starts executing from the first line of the main() function and ends at the closing curly brace on the last line.
Example
The structure of the simplest Dart program:
void main() {
// Write your code here
print('Welcome to EXAMPLE Dart Tutorial!');
}
欢迎来到 EXAMPLE Dart 教程!
Let's break down each part of this code:
| Code elements | Description |
|---|---|
| void | Return type; void indicates that the function does not return any value |
| main | Function name; this is the entry function name specified by Dart and cannot be changed |
| () | Parameter list; main() can accept no parameters, or it can accept command-line arguments |
| { } | Function body; the code inside the curly braces is what the function executes |
| print() | Built-in function, used to output text to the console |
| ; | Statement terminator; every statement in Dart must end with a semicolon |
Dart strictly requires every statement to end with a semicolon (;). Forgetting the semicolon is the most common syntax error among beginners. Fortunately, the Dart plugin in VS Code automatically indicates where semicolons are missing.
The main() Function with Command-Line Arguments
The main() function can accept a list of strings as command-line arguments:
Example
void main(List<String> args) {
// Print the number of arguments
print('Number of arguments: ${args.length}');
// Iterate over and print each argument
for (var i = 0; i < args.length; i++) {
print('Argument $i: ${args[i]}');
}
}
$ dart run hello.dart example dart 教程 参数个数:3 参数 0: example 参数 1: dart 参数 2: 教程
This uses the List type and a for loop, which we will cover in detail in later chapters.
Comment syntax
Comments are explanations of the code; the compiler ignores comment content.
Good comments help others (including yourself a few months later) understand the intent of the code more quickly.
Dart supports three comment styles:
| Type | Syntax | Applicable scenarios |
|---|---|---|
| Single-line comment | // comment content | Briefly explain the purpose of a line of code |
| Multi-line comment | /* Comment content */ | Detailed explanation spanning multiple lines |
| Documentation comment | /// Documentation comments | Generate API documentation for functions and classes |
Example
/// Documentation comments can be used to generate HTML documentation with the [dart doc] command
void main() {
// Single-line comment: prints welcome message
print('Welcome to learn Dart!'); // Inline comment: this is also valid
/*
* Multi-line comment: suitable for longer explanations
* Second line comment
* Third line comment
*/
print('EXAMPLE Tutorial - Dart Basic Syntax');
}
欢迎学习 Dart! EXAMPLE 教程 - Dart 基础语法
The principle of comments is to "explain why, not what." The code itself already shows what it does; comments should explain why it is written this way, or provide background information that the code cannot express.
Statements and Expressions
In Dart, code is composed of statements and expressions.
Understanding the difference between the two helps you better organize your code logic.
Expression
An expression is a piece of code that can be evaluated, and it produces a value.
Example
// Each of the following lines is an expression; they all produce a value.
42; // Literal expression, value is 42
3 + 5; // Arithmetic expression, value is 8
'Hello'.length; // Property access expression, value is 5
(10 > 5); // Relational expression, value is true
}
Statement
A statement is an instruction that performs an action, and it does not produce a value.
Example
// Variable declaration statement: declares a variable and assigns a value
var name = 'EXAMPLE';
// Function call statement: calls print() to perform an output action
print(name);
// Control flow statement: decides which code to execute based on conditions
if (name.length > 3) {
print('Name length is greater than 3');
}
}
EXAMPLE 名称长度大于 3
In short:Expressions produce values, statements perform actions.
You can use expressions where a value is needed, but you cannot use statements.
A common misconception is treating all code as "statements." In reality, many constructs in Dart (such as function calls and variable assignments) are themselves expressions, which means they can be nested. This is a shared characteristic of Dart and other C-family languages.
Identifier naming conventions
An identifier is the name you give to code elements such as variables, functions, and classes.
Dart has some rules and conventions for identifiers:
Naming rules (must be followed)
Identifiers can only consist of letters, digits, underscores (_), and dollar signs ($).
Identifiers cannot start with a number.
Identifiers cannot be Dart reserved keywords (such as class, if, var, etc.).
Naming conventions (recommended)
| Code elements | Naming conventions | Example |
|---|---|---|
| Class name | UpperCamelCase | StudentInfo、HttpClient |
| Enumeration type | UpperCamelCase | Color、Status |
| Library and file names | lowercase_with_underscores | my_utils、user_service |
| Variable Name | lowerCamelCase | userName、maxCount |
| Function Name | lowerCamelCase | getUserInfo()、calculateTotal() |
| Constant name | lowerCamelCase | piValue、defaultPort |
| Private members | Underscore prefix | _internalState、_privateMethod() |
Example
Practical applications of various naming styles:
class UserAccount {
// Public members: lowerCamelCase
String userName;
// Private members: underscore prefix (only accessible within this file)
String _password;
// constructor
UserAccount(this.userName, this._password);
// Public methods: lower camelCase
bool verifyPassword(String input) {
return input == _password;
}
// Private methods: underscore prefix
void _encryptPassword() {
// Encryption logic...
}
}
// Entry function: lowercase
void main() {
// Variable names: lower camelCase
var userAccount = UserAccount('example', '123456');
// Constants: lower camelCase (Dart style)
const maxLoginAttempts = 3;
print('Username: ${userAccount.userName}');
print('Maximum login attempts: $maxLoginAttempts');
}
用户名: example 最大登录尝试次数: 3
In Dart's naming conventions, constants use lowerCamelCase, rather than the all-caps with underscores style (UPPER_CASE) common in other languages. This is a unique style of the Dart community, so be sure to keep it in mind.
