The first Dart program

Learning a programming language—the best way is not to memorize grammar rules first, but to get a program running, and then ask line by line what it means.

In this chapter, we will start from the simplest program and gradually expand it into a slightly more complete small program, going through the most basic concepts of Dart along the way.

Dart language standard file suffix.dart, for examplehello.dart。


The simplest program: Hello, Dart!

Open DartPadhttps://dartpad.dev(or create a hello.dart file in a local editor), enter the following code:

Example

void main() {
  print('Hello, Dart!');
}

Click run, output:

Hello, Dart!

Command to run in local environment:

dart hello.dart

Just these 3 lines of code. Now let's understand every character.


Line-by-line analysis

void main() {

This is the entry function declaration of the program. Dart programs always start executing from main().

Let's break it down:

PartMeaning
voidReturn type. void means "this function returns nothing after execution."
mainFunction name. This is the Dart-conventional entry function name; it cannot be changed to anything else.
()Parameter list. It is empty here, meaning the main function accepts no parameters.
{The beginning of the function body. It pairs with the } on the last line and wraps 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.

Let's break it down:

PartMeaning
printBuilt-in function name, used to output a line of text to the console.
(...)Parameter list of a function call
'Hello, Dart!'A string literal, enclosed in single quotes '.
;Statement terminator. Every statement must end with a semicolon.
The leading two spacesIndentation, indicating that this line of code belongs inside the main() function. Dart convention uses 2 spaces for indentation.

}

The closing 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 either single quotes or double quotes; they are completely equivalent.

Example

void main() {
  print('Hello, Dart!');   // Single quotes
  print("Hello, Dart!");   // Double quotes, same effect
}
Hello, Dart!
Hello, Dart!

When should you use which type of quote? You can refer to the following scenarios:

ScenariosRecommendedExample
Normal caseSingle quotes (Dart community convention)'Hello'
String contains single quotesDouble quotes"It's a beautiful day!"
String contains double quotesSingle quotes'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 going forward.


Comments

Comments are explanatory text written for humans; the Dart compiler completely ignores them.

Example

void main() {
  // This is a single-line comment, from // to end of 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 display documentation comments as hover tooltips.
}
Comment typesSyntaxPurpose
Single-line comment// contentExplain a line of code
Multi-line comment/* content */Comment out a block of code, or write a longer explanation
Documentation comment/// contentFor describing APIs and generating documentation

Good comments explain "why," not "what was done." The code itself already shows "what was done"; comments should supplement the reason or intent behind it.


Variables: naming data

A program cannot only output fixed text; we need variables to store and use data.

Example

void main() {
  String name = 'EXAMPLE';
  int age = 25;
  double height = 1.68;
  bool isStudent = true;

  print(name);
  print(age);
  print(height);
  print(isStudent);
}
EXAMPLE
25
1.68
true

Variable declaration format

类型名  变量名  =  初始值  ;
 │       │         │    └─ 语句结束符
 │       │         └─ 赋值运算符
 │       └─ 你给这个数据起的名字
 └─ 告诉 Dart 这个变量存储什么类型的数据

Quick overview of basic data types

TypeDescriptionExample
StringText string'EXAMPLE'、"hello"
intInteger25、-10、0
doubleDecimals (floating-point numbers)1.68、3.14
boolBoolean value (true/false)true、false

The details of data types will be covered in later chapters; here we just get a preliminary impression.


Use var to automatically infer the type

It's a bit tedious to write the type name every time.

Dart supports using the var keyword to automatically infer the variable type—the compiler determines the type based on the value you assign.

Example

void main() {
  var name = 'EXAMPLE';    // 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);
}
EXAMPLE
25

The type inferred by var is determined at compile time; after that, you cannot assign a value of a different type to it.

Example

void main() {
  var name = 'EXAMPLE';
  name = 'Bob';    // OK, still String
  // name = 123; // Error: cannot assign int to a variable of type String
}

When should you use var, and when should you explicitly write the type?

ScenariosRecommendedReason
Local variables, the type is obvious at a glancevarMore concise
Function parameters, class fields, and return types.Specify typeCode is clearer and 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 = 'EXAMPLE';
  var age = 25;

  print('My name is $name, and I am $age years old.');
  print('Next year I will be ${age + 1} years old.');
}
我叫 EXAMPLE,今年 25 岁。
明年我将 26 岁。
SyntaxPurposeExample
$variableNameDirectly embed variable values, concise$name
${expression}Embed any expression (calculation, method call, etc.).${age + 1}、${name.toUpperCase()}

Compared to string concatenation like print('My name is ' + name + ', this year ' + age.toString() + ' years old.'), interpolation syntax is clearer, safer, and the idiomatic style in Dart.


A slightly more complete small program

Now let's combine what we've learned earlier and write a slightly more realistic program: a simple self-introduction generator.

Example

void main() {
  // Personal information
  var name = 'EXAMPLE';
  var age = 25;
  var city = 'Shanghai';
  var isStudent = false;
  var hobby = 'Dart programming';

  // Generate introduction: ternary operator determines identity
  var occupation = isStudent ? 'Student' : 'Professional';

  print('=============================');
  print(' Personal Profile');
  print('=============================');
  print('Name: $name');
  print('Age: $age');
  print('City: $city');
  print('Identity: $occupation');
  print('Hobby: $hobby');
  print('-----------------------------');
  print('Hello everyone, I am $name from $city,');
  print('I am $age years old this year, and I am a $occupation.');
  print('My hobby is ${hobby}, nice to meet you all!');
  print('=============================');
}
=============================
       个人简介
=============================
姓名:EXAMPLE
年龄:25 岁
城市:上海
身份:职场人
爱好:Dart 编程
-----------------------------
大家好,我是来自上海的EXAMPLE,
今年 25 岁,是一名职场人。
我的爱好是Dart 编程,很高兴认识大家!
=============================

New syntax: ternary operator

Example

var occupation = isStudent ? 'Student' : 'Professional';

This is Dart's ternary operator, formatted as:

condition ? value when the condition is true : value when the condition is false

Equivalent to the following if/else form:

Example

String occupation;
if (isStudent) {
  occupation = 'Student';
} else {
  occupation = 'Professional';
}

The ternary operator is very concise when a value has only two possibilities. Later chapters will introduce the full usage of if/else in detail.


Code style: Dart writing conventions.

Good code style makes code more readable and professional.

Dart has an official recommended style guide; at the beginner stage, mastering the following points is enough.

Use 2 spaces for indentation

Example

// Correct: 2 spaces
void main() {
  print('Hello');
}

// Not recommended: 4 spaces (common in other languages, but the Dart community prefers 2)

Variable and function names use lowerCamelCase (lowerCamelCase).

Example

var firstName = 'EXAMPLE';     // lower camel case: correct
// var first_name = 'EXAMPLE'; // underscore style: not Dart convention
// var FirstName = 'EXAMPLE'; // PascalCase: reserved for class names

Class names use UpperCamelCase.

Example

class UserProfile { }   // correct
// class user_profile { } // Incorrect
// class userProfile { } // Incorrect

Constants use lower camel case (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 to automatically format.

You don't have to memorize the rules; just run in the project directory:

$ dart format .

Dart's official formatting tool automatically adjusts code to the standard style; in VS Code, you can also configure automatic formatting on save.


Common errors and explanations

Beginners often encounter the following errors when writing their first program; let's get familiar with them.

Error 1: Forgetting the semicolon

Example

void main() {
  print('Hello, Dart!')  // missing ;
}

Error message:

Error: Expected ';' after this.

Solution: add ; at the end of the statement.

Error 2: Mismatched parentheses

Example

void main() {
  print('Hello, Dart!'   // missing right parenthesis )
}

Error message:

Error: Expected ')' before this.

Solution: carefully check that every ( has a corresponding ). VS Code will highlight mismatched brackets.

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 type of quote.

Error 4: main misspelled

Example

void Main() {  // M is capitalized
  print('Hello, Dart!');
}

Dart is case-sensitive; Main and main are completely different names.

The program compiles, but it will report 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;
  print(name);  // name is not initialized
}

Dart null-safety error:

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 a nullable type String? name (detailed in later chapters).

other extensions