Dart Syntax


Syntax refers to the set of rules that define how programs are written. Every programming language has its own syntax structure. A Dart program consists of:

The Main Function

Every Dart program starts executing from the main() function. This is the entry point of your application.

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

Output:

Hello, World!

Variables and Data Types

Dart is statically typed, but can infer types using the var keyword.

Declaring Variables

void main() {
// Explicit type declaration
String name = 'Alice';
int age = 30;
double height = 5.9;
bool isStudent = true;

// Type inference with 'var'
var company = 'Tech Corp';
var salary = 50000.00;

print('$name is $age years old and $height feet tall.');
}

Output:

Alice is 30 years old and 5.9 feet tall.

Final and Const

  • final: A variable that can be set only once
  • const: A compile-time constant

void main() {
final city = 'New York';
const country = 'USA';

// city = 'Boston'; // Error: Final variable can't be reassigned
// country = 'Canada'; // Error: Const variables can't be reassigned
}

Basic Operators

Dart supports standard arithmetic and logical operators.

void main() {
int a = 10;
int b = 3;

print(a + b); // 13
print(a - b); // 7
print(a * b); // 30
print(a / b); // 3.333...
print(a ~/ b); // 3 (integer division)
print(a % b); // 1 (modulus)

bool x = true;
bool y = false;
print(x && y); // false
print(x || y); // true
print(!x); // false
}

Control Flow


If-Else Statements

void main() {
int age = 18;

if (age >= 18) {
  print('Adult');
} else {
  print('Minor');
    }
}

For Loops

void main() {
for (int i = 1; i <= 5; i++) {
  print('Count: $i');
    }
}

While Loops

void main() {
int i = 1;
while (i <= 5) {
  print('While count: $i');
  i++;
    }
}

Common Mistakes and Fixes


Missing Semicolons


Mistake:

void main() {
print('Hello') // Missing semicolon
}

Fix:

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

Type Mismatch


Mistake:

void main() {
int age = '25'; // Error: String can't be assigned to int
}