Dart Syntax
Learn the basic rules and structure of Dart programming
📝 Dart Syntax Basics
Dart syntax is clean and easy to read. Every Dart program follows specific rules for writing code. Understanding these basic syntax rules will help you write correct and readable Dart programs.
// Basic Dart syntax example
void main() {
print('Learning Dart syntax is fun!');
}
Output:
Learning Dart syntax is fun!
Essential Syntax Rules
Semicolons
End statements with semicolons
print('Hello World');
Curly Braces
Group code blocks together
void main() {
// code here
}
Case Sensitive
Dart distinguishes between cases
var name = 'John';
var Name = 'Jane'; // Different!
Indentation
Use spaces for readable code
if (true) {
print('Indented code');
}
🔹 Main Function
Every Dart program must have a main() function:
// The main function - program starts here
void main() {
print('Program starts here');
print('This runs first');
print('Then this runs');
}
// Alternative shorter syntax
void main() => print('Short version');
Output:
Program starts here
This runs first
Then this runs
🔹 Statements and Expressions
Understanding the difference between statements and expressions:
🔸 Statements
// Statements perform actions
print('This is a statement');
var age = 25;
if (age > 18) {
print('Adult');
}
🔸 Expressions
// Expressions produce values
var sum = 5 + 3; // 5 + 3 is an expression
var name = 'John'; // 'John' is an expression
var isAdult = age > 18; // age > 18 is an expression
Output:
This is a statement
Adult
🔹 Code Blocks and Scope
Curly braces create code blocks and define variable scope:
void main() {
var globalVar = 'I am global';
if (true) {
var localVar = 'I am local';
print(globalVar); // Can access global
print(localVar); // Can access local
}
print(globalVar); // Can access global
// print(localVar); // Error! Can't access local
}
Output:
I am global
I am local
I am global
🔹 Naming Conventions
Follow these naming rules for clean code:
🔸 Variables and Functions
-
Use
camelCase
:
userName,calculateAge() - Start with lowercase letter
- Use descriptive names
🔸 Classes
-
Use
PascalCase
:
Person,BankAccount - Start with uppercase letter
🔸 Constants
-
Use
lowerCamelCase
:
maxRetries -
Or
SCREAMING_SNAKE_CASE
:
MAX_RETRIES
// Good naming examples
void main() {
var userName = 'john_doe'; // camelCase
var userAge = 25; // camelCase
const maxLoginAttempts = 3; // camelCase
print('User: $userName, Age: $userAge');
}
Output:
User: john_doe, Age: 25
🔹 Common Syntax Patterns
Frequently used Dart syntax patterns:
void main() {
// Variable declaration
var message = 'Hello';
int number = 42;
// String interpolation
print('Message: $message, Number: $number');
// Conditional statement
if (number > 0) {
print('Positive number');
} else {
print('Not positive');
}
// Loop
for (int i = 1; i <= 3; i++) {
print('Count: $i');
}
}
Output:
Message: Hello, Number: 42
Positive number
Count: 1
Count: 2
Count: 3