Dart Syntax and Program Structure – Detailed Notes
Dart is the programming language used by Flutter for building cross-platform applications.
Understanding Dart syntax and program structure is an important foundation before working with
Flutter widgets, UI, APIs, Firebase, state management, and application architecture.
JustAcademy's Flutter curriculum includes Dart language introduction and Dart programming fundamentals
covering variables, data types, operators, control statements, functions, OOP, collections, and
asynchronous programming. :contentReference[oaicite:0]{index=0}
Learn more about the complete Flutter course here:
JustAcademy Flutter Training
You can also register for a course demo here:
Register for Flutter Course Demo
1. What is Dart Syntax?
Syntax refers to the rules used to write a valid program in a programming language.
Dart syntax defines how variables, functions, classes, statements, expressions, comments,
operators, and other programming elements should be written.
For example:
void main() {
print("Hello, Dart!");
}
This simple program contains a main() function and a print()
statement. The main() function is the standard entry point for a Dart program.
2. Basic Structure of a Dart Program
A simple Dart program generally follows this structure:
// Import statements
// Constants or variables
// Functions
// Classes
void main() {
// Program execution starts here
}
For example:
String appName = "My Dart App";
void greetUser() {
print("Welcome to $appName");
}
void main() {
greetUser();
}
Important Parts
- Import statements: Used to access libraries and packages.
- Variables: Store data used by the program.
- Functions: Contain reusable blocks of logic.
- Classes: Define objects and application structures.
- main(): Entry point from which execution begins.
3. The main() Function
The main() function is the starting point of a normal Dart application.
Statements inside it execute when the program starts.
void main() {
print("Program started");
print("Learning Dart");
}
Output:
Program started
Learning Dart
main() with Arguments
void main(List<String> arguments) {
print(arguments);
}
The optional parameter can receive command-line arguments when a Dart application is executed
from a command-line environment.
4. Statements in Dart
A statement is an instruction that tells the program to perform an action.
Most Dart statements end with a semicolon (;).
void main() {
int age = 25;
print(age);
}
Here, int age = 25; and print(age); are statements.
5. Semicolon in Dart
Semicolons are normally used to terminate statements.
int age = 20;
String name = "Rahul";
print(name);
However, Dart uses curly braces to define blocks, so a closing curly brace does not normally
require a semicolon.
void greet() {
print("Hello");
}
6. Comments in Dart
Comments are used to explain code. They are ignored by the Dart compiler.
Single-Line Comments
// This is a single-line comment
print("Hello");
Multi-Line Comments
/*
This is a multi-line comment.
It can contain multiple lines.
*/
print("Hello Dart");
Documentation Comments
Dart also supports documentation comments using ///.
/// Calculates the total price.
double calculateTotal(double price, int quantity) {
return price * quantity;
}
7. Variables in Dart
Variables are used to store data. Dart provides explicit types as well as type inference.
int age = 25;
double price = 499.99;
String name = "Amit";
bool isActive = true;
Using var
var name = "Amit";
var age = 25;
var price = 99.50;
Dart can infer the type from the assigned value.
Using dynamic
dynamic value = 100;
value = "Hello";
value = true;
dynamic allows a variable to hold values of different types, but it should be used
carefully because it reduces some of the benefits of static type checking.
8. Constants: final and const
final
A final variable can be assigned only once.
final String name = "Flutter";
print(name);
const
A const value represents a compile-time constant.
const double pi = 3.14159;
const int maxUsers = 100;
Difference
Keyword |
Purpose |
Example |
|---|
var |
Type is inferred and the variable can normally be reassigned. |
var name = "John"; |
final |
Value can be assigned only once. |
final age = 25; |
const |
Compile-time constant. |
const pi = 3.14; |
9. Data Types
Dart provides several commonly used data types:
int – Integer numbers
double – Decimal numbers
num – Integer or decimal numbers
String – Text
bool – True or false
List – Ordered collection
Set – Collection of unique values
Map – Key-value collection
Object – Base type for Dart objects
dynamic – Dynamically typed value
int age = 22;
double salary = 45000.50;
String city = "Mumbai";
bool employed = true;
10. String Syntax
Strings can be written using single or double quotation marks.
String name = 'Rahul';
String city = "Mumbai";
String Interpolation
Dart uses the $ symbol to insert variables into strings.
String name = "Rahul";
int age = 25;
print("My name is $name");
print("I am $age years old");
Expressions can be placed inside ${}.
int a = 10;
int b = 20;
print("Total = ${a + b}");
11. Operators in Dart
Dart supports different categories of operators.
Arithmetic Operators
int a = 20;
int b = 10;
print(a + b);
print(a - b);
print(a * b);
print(a / b);
print(a % b);
Comparison Operators
print(a == b);
print(a != b);
print(a > b);
print(a < b);
print(a >= b);
print(a <= b);
Logical Operators
bool isStudent = true;
bool hasId = true;
print(isStudent && hasId);
print(isStudent || hasId);
print(!isStudent);
12. Conditional Statements
Conditional statements allow a program to make decisions.
if Statement
int age = 20;
if (age >= 18) {
print("Adult");
}
if-else Statement
int age = 16;
if (age >= 18) {
print("Eligible");
} else {
print("Not eligible");
}
else-if
int marks = 85;
if (marks >= 90) {
print("Grade A+");
} else if (marks >= 75) {
print("Grade A");
} else if (marks >= 60) {
print("Grade B");
} else {
print("Needs improvement");
}
13. switch Statement
A switch statement can be used when a value needs to be compared with multiple cases.
String day = "Monday";
switch (day) {
case "Monday":
print("Start of the week");
break;
case "Friday":
print("Weekend is near");
break;
default:
print("Regular day");
}
Modern Dart also provides pattern matching and enhanced switch capabilities, but beginners
should first understand the basic decision-making structure.
14. Loops in Dart
for Loop
for (int i = 1; i <= 5; i++) {
print(i);
}
while Loop
int i = 1;
while (i <= 5) {
print(i);
i++;
}
do-while Loop
int i = 1;
do {
print(i);
i++;
} while (i <= 5);
for-in Loop
List<String> fruits = ["Apple", "Banana", "Mango"];
for (String fruit in fruits) {
print(fruit);
}
15. Functions in Dart
Functions are reusable blocks of code that perform a particular task.
void greet() {
print("Hello Dart");
}
void main() {
greet();
}
Function with Parameters
void greetUser(String name) {
print("Hello $name");
}
void main() {
greetUser("Rahul");
}
Function with Return Value
int add(int a, int b) {
return a + b;
}
void main() {
int result = add(10, 20);
print(result);
}
Arrow Function
int square(int number) => number * number;
16. Lists
A List stores an ordered collection of values.
List<String> languages = [
"Dart",
"Java",
"Python"
];
print(languages[0]);
Adding Data
languages.add("JavaScript");
Looping Through a List
for (String language in languages) {
print(language);
}
17. Sets
A Set stores unique values.
Set<String> skills = {
"Dart",
"Flutter",
"Firebase"
};
skills.add("Dart");
print(skills);
Adding an already existing value does not create another duplicate entry.
18. Maps
A Map stores data as key-value pairs.
Map<String, dynamic> user = {
"name": "Rahul",
"age": 25,
"city": "Mumbai"
};
print(user["name"]);
print(user["city"]);
19. Classes and Objects
Dart is an object-oriented programming language. Classes are used to define the structure and
behavior of objects.
class Student {
String name;
int age;
Student(this.name, this.age);
void display() {
print("Name: $name");
print("Age: $age");
}
}
void main() {
Student student = Student("Rahul", 22);
student.display();
}
Structure of the Example
class Student defines a class.
name and age are properties.
Student() is a constructor.
display() is a method.
Student("Rahul", 22) creates an object.
20. Constructors
Constructors are used to initialize objects.
class Product {
String name;
double price;
Product(this.name, this.price);
}
void main() {
Product product = Product("Laptop", 55000);
print(product.name);
print(product.price);
}
21. Named Parameters
Named parameters make function calls easier to understand.
void createUser({
required String name,
required int age,
}) {
print("Name: $name");
print("Age: $age");
}
void main() {
createUser(
name: "Rahul",
age: 25,
);
}
22. Null Safety
Dart uses null safety to distinguish between values that can contain null and
values that should not be null.
String name = "Rahul";
String? middleName = null;
The ? indicates that the variable can contain a null value.
Null-Aware Access
String? name;
print(name?.length);
23. Import Statements
Dart programs can import libraries to use additional functionality.
import 'dart:math';
void main() {
print(sqrt(25));
}
In Flutter projects, imports are also commonly used to access Flutter framework libraries
and application files.
import 'package:flutter/material.dart';
import 'screens/home_screen.dart';
24. Library and File Organization
As an application grows, code should be divided into multiple files instead of placing
everything inside one Dart file.
my_flutter_app/
├── lib/
│ ├── main.dart
│ ├── models/
│ │ └── user.dart
│ ├── screens/
│ │ └── home_screen.dart
│ ├── widgets/
│ │ └── custom_button.dart
│ ├── services/
│ │ └── api_service.dart
│ └── utils/
│ └── constants.dart
├── test/
└── pubspec.yaml
The exact project structure can vary according to the application's architecture, but separating
screens, models, services, widgets, and utility code can make a project easier to maintain.
25. A Complete Dart Program
The following example combines variables, a function, a condition, a list, and a class.
class Student {
String name;
int age;
Student(this.name, this.age);
void display() {
print("Student: $name");
print("Age: $age");
}
}
int calculateTotal(List<int> marks) {
int total = 0;
for (int mark in marks) {
total += mark;
}
return total;
}
void main() {
Student student = Student("Rahul", 21);
List<int> marks = [80, 85, 90];
int total = calculateTotal(marks);
double average = total / marks.length;
student.display();
print("Total: $total");
print("Average: $average");
if (average >= 75) {
print("Good performance");
} else {
print("Needs improvement");
}
}
26. Dart Program Execution Flow
A simple Dart program can be understood through the following execution flow:
- The Dart runtime starts the application.
- The
main() function is called.
- Variables are initialized.
- Functions are called when required.
- Conditions and loops control program execution.
- Objects and methods can be used for object-oriented logic.
- The program continues until execution is complete.
27. Dart Syntax Rules to Remember
Rule |
Example |
|---|
Statements generally end with semicolons |
print("Hello"); |
Code blocks use curly braces |
if (condition) { ... } |
Variables can have explicit types |
int age = 20; |
Type inference is supported |
var name = "John"; |
Strings use quotes |
String name = "John"; |
Functions contain reusable logic |
void greet() { } |
Classes define objects |
class Student { } |
Comments begin with // or /* */ |
// Comment |
Nullable types use ? |
String? name; |
28. Best Practices for Writing Dart Code
- Use meaningful variable and function names.
- Keep functions focused on a specific task.
- Use strong typing where it improves clarity.
- Prefer
final when a variable does not need reassignment.
- Use
const for compile-time constant values.
- Use null safety rather than relying on unchecked null values.
- Break large programs into multiple files and reusable classes.
- Use comments and documentation where they provide useful context.
- Keep indentation and formatting consistent.
- Practice Dart fundamentals before moving deeply into Flutter widgets and architecture.
29. Dart Syntax in Flutter Development
Dart syntax becomes especially important when working with Flutter because Flutter applications
are written using Dart. JustAcademy's Flutter curriculum places Dart programming fundamentals
before major Flutter UI topics, including widgets, layouts, navigation, APIs, Firebase,
and state management. :contentReference[oaicite:1]{index=1}
For example, a basic Flutter application uses Dart syntax like this:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("My Flutter App"),
),
body: const Center(
child: Text("Hello Flutter"),
),
),
);
}
}
This example demonstrates how Dart's imports, main(), classes, constructors,
methods, parameters, and expressions are used to create a Flutter application.
30. Quick Revision
- Dart: Programming language used by Flutter.
- main(): Standard entry point of a Dart application.
- Statement: An instruction executed by the program.
- Variable: Stores data.
- Function: Reusable block of code.
- Class: Blueprint for creating objects.
- Object: Instance of a class.
- List: Ordered collection.
- Set: Collection of unique values.
- Map: Key-value collection.
- final: Can be assigned once.
- const: Compile-time constant.
- ?: Used to declare a nullable type.
- import: Brings libraries or other files into a Dart file.
31. Practice Exercises
- Write a Dart program that prints your name, age, and city.
- Create a program that calculates the sum of two numbers.
- Write an if-else program to check whether a number is positive or negative.
- Create a loop that prints numbers from 1 to 10.
- Create a List containing five programming languages and print each value.
- Create a Map containing a user's name, email, and age.
- Create a
Student class with name, age, and marks properties.
- Create a function that calculates the average of three numbers.
- Create a Dart program demonstrating
final and const.
- Create a simple Flutter application using the Dart program structure explained above.
32. Conclusion
Dart syntax and program structure form the foundation of Flutter development. A strong
understanding of main(), variables, data types, operators, conditions, loops,
functions, collections, classes, objects, constructors, imports, and null safety makes it
easier to understand and write Flutter applications.
JustAcademy's Flutter training includes Dart programming fundamentals such as variables,
data types, operators, control statements, functions, OOP, collections, and asynchronous
programming as part of its curriculum. :contentReference[oaicite:2]{index=2}
Explore the complete course:
https://www.justacademy.co/course-detail/flutter-training
Register for a course demo:
https://www.justacademy.co/register-for-course-demo