Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Dart Basic Syntax

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 a Dart program, how to write comments, the difference between statements and expressions, and the naming conventions for identifiers.


Program Structure and the main() Function

Dart filenames use the .dart suffix, and every Dart program must have an entry point - the main() function.

The program starts executing at the first line of main() and ends at the closing brace on the last line.

Example

The structure of a minimal Dart program:

// Program entry: the main() function is the starting point of a Dart program

void

main

(

)

{

 

// Write your code here

  print

(

'Welcome to the RUNOOB Dart Tutorial!'

)

;

}



欢迎来到 RUNOOB Dart 教程!

Let us break down each part of this code:

Code element Description
void Return type; void means the function returns no value
main Function name; this is the entry function name defined by Dart and cannot be changed
() Parameter list; main() can take no parameters or can take command-line arguments
{ } Function body; the code inside the 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 for beginners. Fortunately, the Dart plugin for VS Code automatically hints where a semicolon is missing.

The main() Function with Command-Line Arguments

The main() function can accept a list of strings as command-line arguments:

Example

// List args receives the list of arguments passed from the command line

void

main

(

List

<

String

args

)

{

// Output the number of arguments

  print

(

'Number of arguments: ${args.length}'

)

;

 

// Iterate over and print each argument

 

for

(

var

i

=

0

;

i

&

lt

;

args.

length

;

i

++

)

{

    print

(

'Argument $i: ${args[i]}'

)

;

 

}

}



$ dart run hello.dart runoob dart 教程

参数个数:3

参数 0: runoob

参数 1: dart

参数 2: 教程

This uses the List type and for loops, which we will cover in detail in later chapters.


Writing Comments

Comments explain the code; the compiler ignores their content.

Good comments help others (including yourself a few months later) understand the intent of the code faster.

Dart supports three kinds of comments:

Type Syntax Applicable scenarios
Single-line comment // Comment content A brief explanation of what a line of code does
Multi-line comment /* Comment content */ Detailed explanation spanning multiple lines
Documentation comment /// Documentation comment Generate API documentation for functions and classes

Example

/// This is a documentation comment describing the program's functionality

/// Documentation comments can generate HTML docs with the [dart doc] command

void

main

(

)

{

 

// Single-line comment: output a welcome message

  print

(

'Welcome to learning Dart!'

)

;

// Inline comment: this is also valid

 

/*
   * Multi-line comment: suitable for longer explanations
   * Second line of the comment
   * Third line of the comment
   */

  print

(

'RUNOOB Tutorial - Dart Basic Syntax'

)

;

}



欢迎学习 Dart!

RUNOOB 教程 - Dart 基础语法

The principle of comments is "explain why, not what". The code itself already tells what it does; comments should explain why it is written this way, or add background information that the code cannot express.


Statements and Expressions

In Dart, code consists of statements (Statement) and expressions (Expression).

Understanding the difference between the two helps you organize code logic better.

Expression

An expression is a piece of code that can be evaluated and produces a value.

Example

void

main

(

)

{

 

// Each line below 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; it does not produce a value.

Example

void

main

(

)

{

 

// Variable declaration statement: declare a variable and assign a value

 

var

name

=

'RUNOOB'

;

 

// Function call statement: call print() to perform an output action

  print

(

name

)

;

 

// Control flow statement: decide which code to execute based on a condition

 

if

(

name.

length

3

)

{

    print

(

'Name length is greater than 3'

)

;

 

}

}



RUNOOB

名称长度大于 3

Simply put: expressions produce values, statements perform actions.

You can use an expression where a value is needed, but not a statement.

A common misconception is treating all code as "statements". In fact, many constructs in Dart (such as function calls and variable assignments) are themselves expressions, which means they can be nested. This is a shared feature of Dart and other C-family languages.


Identifier Naming Conventions

An identifier (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 digit.

Identifiers cannot be Dart reserved keywords (such as class, if, var, etc.).

Naming conventions (recommended)

Code element Naming style Example
Class Names UpperCamelCase StudentInfo, HttpClient
Enumeration Type UpperCamelCase Color, Status
Library names, file names lowercase + underscores (lowercase_with_underscores) my_utils, user_service
Variable Name lowerCamelCase userName, maxCount
Function name lowerCamelCase getUserInfo(), calculateTotal()
Constant names lowerCamelCase piValue, defaultPort
Private members Underscore prefix _internalState, _privateMethod()

Example

Practical use of the various naming styles:

// Class name: UpperCamelCase

class

UserAccount

{

 

// Public member: lowerCamelCase

  String userName

;

 

// Private member: underscore prefix (accessible only within this file)

  String _password

;

 

// Constructor

  UserAccount

(

this

.

userName

,

this

._password

)

;

 

// Public method: lowerCamelCase

 

bool

verifyPassword

(

String input

)

{

   

return

input

==

_password

;

 

}

 

// Private method: underscore prefix

 

void

_encryptPassword

(

)

{

   

// Encryption logic...

 

}

}

// Entry function: lowercase

void

main

(

)

{

 

// Variable name: lowerCamelCase

 

var

userAccount

=

UserAccount

(

'runoob'

,

'123456'

)

;

 

// Constant: lowerCamelCase (Dart style)

 

const

maxLoginAttempts

=

3

;

  print

(

'Username: ${userAccount.userName}'

)

;

  print

(

'Max login attempts: $maxLoginAttempts'

)

;

}



用户名: runoob

最大登录尝试次数: 3

In Dart's naming conventions, constants use lowerCamelCase, not the all-caps + underscores (UPPER_CASE) common in other languages. This is a unique style of the Dart community, so be sure to note it.