What is Dart?
Dart is a modern, object-oriented programming language developed by Google. It is the primary programming language used for building applications with Flutter. Dart is designed to support application development across multiple platforms and provides features such as variables, functions, classes, collections, asynchronous programming, null safety, and object-oriented programming.
In Flutter development, Dart is used to write application logic, create widgets, manage application state, communicate with APIs, work with databases, and implement complete application functionality. JustAcademy's Flutter curriculum includes Dart programming fundamentals such as variables, data types, operators, control statements, functions, object-oriented programming, collections, and asynchronous programming. JustAcademy Flutter Training
1. Why is Dart Used with Flutter?
Flutter uses Dart as its programming language. When developers build a Flutter application, the application's business logic and user-interface code are generally written in Dart.
For example, a Flutter application can use Dart to:
- Create widgets and application screens
- Handle user interactions
- Define variables and application data
- Create reusable functions
- Build classes and objects
- Manage application state
- Make API requests
- Parse JSON data
- Work with local databases
- Implement asynchronous operations
- Handle errors and exceptions
- Implement application business logic
2. Basic Dart Program
The following is a simple Dart program:
void main() {
print('Hello, Dart!');
}
The main() function is the entry point of a Dart program. The print() function displays information in the console.
3. Dart Variables
Variables are used to store data in a Dart program. Dart provides several ways to declare variables depending on whether the type should be explicitly specified or inferred.
Example
String name = 'Rahul';
int age = 25;
double salary = 45000.50;
bool isStudent = false;
Using var
var name = 'Rahul';
var age = 25;
var price = 999.50;
With var, Dart can infer the type from the value assigned to the variable.
4. Dart Data Types
Dart provides several built-in data types that are commonly used in application development.
| Data Type |
Purpose |
Example |
| int |
Whole numbers |
int age = 25; |
| double |
Decimal numbers |
double price = 99.99; |
| String |
Text |
String name = 'Amit'; |
| bool |
True/false values |
bool active = true; |
| List |
Ordered collection |
List names = []; |
| Set |
Unique collection |
Set numbers = {}; |
| Map |
Key-value collection |
Map user = {}; |
5. String in Dart
Strings are used to represent text.
String firstName = 'Rahul';
String lastName = 'Sharma';
print(firstName);
print(lastName);
String Interpolation
Dart supports string interpolation using the $ symbol.
String name = 'Rahul';
int age = 25;
print('My name is $name');
print('I am $age years old');
Expressions can also be inserted using ${}.
int a = 10;
int b = 20;
print('Total: ${a + b}');
6. Operators in Dart
Operators are used to perform calculations, comparisons, assignments, and logical operations.
Arithmetic Operators
int a = 10;
int b = 3;
print(a + b);
print(a - b);
print(a * b);
print(a / b);
print(a % b);
Comparison Operators
int age = 20;
print(age == 20);
print(age != 18);
print(age > 18);
print(age < 30);
print(age >= 18);
print(age <= 25);
Logical Operators
bool isLoggedIn = true;
bool isAdmin = false;
print(isLoggedIn && isAdmin);
print(isLoggedIn || isAdmin);
print(!isAdmin);
7. Conditional Statements
Conditional statements allow a program to execute different code depending on a condition.
if Statement
int age = 22;
if (age >= 18) {
print('You are eligible.');
}
if-else Statement
int age = 16;
if (age >= 18) {
print('Adult');
} else {
print('Minor');
}
else-if Statement
int marks = 75;
if (marks >= 90) {
print('Grade A+');
} else if (marks >= 75) {
print('Grade A');
} else if (marks >= 60) {
print('Grade B');
} else {
print('Needs Improvement');
}
8. switch Statement
A switch statement can be used when a program needs to compare a value against multiple possible cases.
String day = 'Monday';
switch (day) {
case 'Monday':
print('Start of the week');
break;
case 'Friday':
print('Almost weekend');
break;
default:
print('Regular day');
}
9. Loops in Dart
Loops are used when a block of code needs to execute repeatedly.
for Loop
for (int i = 1; i <= 5; i++) {
print(i);
}
while Loop
int count = 1;
while (count <= 5) {
print(count);
count++;
}
do-while Loop
int number = 1;
do {
print(number);
number++;
} while (number <= 5);
10. Functions in Dart
Functions are reusable blocks of code that perform a specific task.
Simple Function
void greet() {
print('Welcome to 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);
}
11. Arrow Functions
Dart supports concise arrow syntax for functions containing a single expression.
int square(int number) => number * number;
void main() {
print(square(5));
}
12. Lists in Dart
A List is an ordered collection of values.
List fruits = [
'Apple',
'Banana',
'Mango',
];
print(fruits[0]);
Adding an Item
fruits.add('Orange');
Removing an Item
fruits.remove('Banana');
Looping Through a List
for (String fruit in fruits) {
print(fruit);
}
13. Sets in Dart
A Set is a collection designed to contain unique values.
Set numbers = {
10,
20,
30,
20,
};
print(numbers);
Duplicate values are not retained as separate elements in a Set.
14. Maps in Dart
A Map stores information using key-value pairs.
Map user = {
'name': 'Rahul',
'age': 25,
'city': 'Mumbai',
};
print(user['name']);
print(user['age']);
15. Object-Oriented Programming in Dart
Dart is an object-oriented programming language. Object-oriented programming allows developers to organize application code using classes and objects.
Important OOP concepts in Dart include:
- Classes
- Objects
- Constructors
- Encapsulation
- Inheritance
- Polymorphism
- Abstraction
16. Classes and Objects
A class acts as a blueprint for creating objects.
class Student {
String name = 'Rahul';
int age = 22;
void displayInfo() {
print('Name: $name');
print('Age: $age');
}
}
void main() {
Student student = Student();
student.displayInfo();
}
17. Constructors in Dart
A constructor is used to initialize an object when it is created.
class Student {
String name;
int age;
Student(this.name, this.age);
void displayInfo() {
print('Name: $name');
print('Age: $age');
}
}
void main() {
Student student = Student('Rahul', 22);
student.displayInfo();
}
18. Named Constructors
Dart supports named constructors, which can provide additional ways to create objects.
class User {
String name;
User(this.name);
User.guest() : name = 'Guest';
}
void main() {
User user = User.guest();
print(user.name);
}
19. Inheritance
Inheritance allows one class to reuse or extend functionality from another class.
class Animal {
void eat() {
print('Animal is eating');
}
}
class Dog extends Animal {
void bark() {
print('Dog is barking');
}
}
void main() {
Dog dog = Dog();
dog.eat();
dog.bark();
}
20. Polymorphism
Polymorphism allows objects of related classes to provide different implementations of the same method.
class Animal {
void sound() {
print('Animal sound');
}
}
class Dog extends Animal {
@override
void sound() {
print('Bark');
}
}
class Cat extends Animal {
@override
void sound() {
print('Meow');
}
}
void main() {
Animal dog = Dog();
Animal cat = Cat();
dog.sound();
cat.sound();
}
21. Abstraction
Abstraction allows developers to define a common interface while hiding implementation details.
abstract class Shape {
void draw();
}
class Circle extends Shape {
@override
void draw() {
print('Drawing Circle');
}
}
void main() {
Circle circle = Circle();
circle.draw();
}
22. Null Safety in Dart
Null safety is an important Dart language feature designed to help developers distinguish between values that can contain null and values that cannot.
String name = 'Rahul';
String? nickname;
print(name);
print(nickname);
The ? indicates that the variable can contain a null value.
Null-Aware Operator
String? name;
print(name ?? 'Guest');
The ?? operator provides a fallback value when the expression on the left is null.
23. Final and Const
Dart provides final and const for values that should not be reassigned.
final
final String name = 'Rahul';
print(name);
A final variable is assigned once.
const
const double pi = 3.14159;
print(pi);
A const value represents a compile-time constant.
24. Exception Handling
Dart provides exception-handling mechanisms such as try, catch, and finally.
void main() {
try {
int result = 10 ~/ 0;
print(result);
} catch (e) {
print('An error occurred: $e');
} finally {
print('Operation completed');
}
}
Exception handling is particularly important when working with APIs, databases, files, authentication, and other operations that can fail.
25. Asynchronous Programming in Dart
Mobile applications frequently perform operations that take time, such as API requests, database operations, file operations, and authentication. Dart provides asynchronous programming features to handle these operations.
Important asynchronous concepts include:
- Future
- async
- await
- Stream
26. Future in Dart
A Future represents a value or result that will become available later.
Future fetchData() async {
return 'Data received';
}
void main() async {
String result = await fetchData();
print(result);
}
27. async and await
The async keyword marks a function as asynchronous, while await waits for an asynchronous operation to complete.
Future loadUser() async {
print('Loading user...');
await Future.delayed(
const Duration(seconds: 2),
);
print('User loaded');
}
void main() async {
await loadUser();
}
28. Stream in Dart
A Stream can provide multiple asynchronous values over time. Streams are useful for situations such as real-time data, events, and continuous updates.
Stream countNumbers() async* {
for (int i = 1; i <= 5; i++) {
await Future.delayed(
const Duration(seconds: 1),
);
yield i;
}
}
void main() async {
await for (final number in countNumbers()) {
print(number);
}
}
29. Dart Functions as First-Class Objects
Functions in Dart can be stored in variables, passed as parameters, and returned from other functions.
void greet(String name) {
print('Hello $name');
}
void executeFunction(
void Function(String) function,
) {
function('Rahul');
}
void main() {
executeFunction(greet);
}
30. Anonymous Functions
An anonymous function is a function without a named declaration.
List names = [
'Rahul',
'Amit',
'Priya',
];
names.forEach((name) {
print(name);
});
31. Arrow Functions with Flutter
Arrow functions are frequently used in Flutter for concise callbacks.
ElevatedButton(
onPressed: () => print('Button clicked'),
child: const Text('Click Me'),
)
32. Dart and JSON Data
Flutter applications commonly communicate with APIs that return JSON data. Dart can convert JSON strings into maps and lists using the dart:convert library.
import 'dart:convert';
void main() {
String jsonString = '''
{
"name": "Rahul",
"age": 25
}
''';
Map user = jsonDecode(jsonString);
print(user['name']);
print(user['age']);
}
33. Dart with REST APIs
Dart can be used with HTTP packages in Flutter applications to communicate with REST APIs. JustAcademy's Flutter curriculum includes REST API integration and JSON handling.
import 'dart:convert';
import 'package:http/http.dart' as http;
Future getUsers() async {
final response = await http.get(
Uri.parse('https://example.com/api/users'),
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
print(data);
} else {
print('Request failed');
}
}
34. Dart in a Flutter Application
Dart is not only used for simple programming exercises. In a Flutter project, Dart is used throughout the application architecture.
lib/
├── main.dart
├── models/
│ └── user.dart
├── screens/
│ └── home_screen.dart
├── widgets/
│ └── user_card.dart
├── services/
│ └── api_service.dart
└── providers/
└── user_provider.dart
In this structure:
main.dart starts the application.
models can contain Dart data models.
screens can contain Flutter UI screens.
widgets can contain reusable Flutter widgets.
services can contain API or database logic.
providers can contain application state-management logic.
35. Complete Dart Example
The following example combines variables, a class, a constructor, a method, a list, and a function.
class Student {
String name;
int age;
Student(this.name, this.age);
void display() {
print('Name: $name');
print('Age: $age');
}
}
int calculateTotal(List marks) {
int total = 0;
for (int mark in marks) {
total += mark;
}
return total;
}
void main() {
Student student = Student('Rahul', 22);
student.display();
List marks = [80, 75, 90];
int total = calculateTotal(marks);
print('Total Marks: $total');
}
36. Dart vs Other Programming Languages
| Feature |
Dart |
JavaScript |
Java |
Kotlin |
Swift |
| Main Usage |
Flutter and application development |
Web and application development |
Enterprise and Android development |
Android and modern application development |
Apple platform development |
| Typing |
Type-safe language |
Dynamic and flexible |
Statically typed |
Statically typed |
Statically typed |
| OOP |
Yes |
Yes |
Yes |
Yes |
Yes |
| Async Programming |
Future, async/await, Stream |
Promises, async/await |
Threads, futures and concurrency APIs |
Coroutines |
Async/await and concurrency features |
| Flutter Integration |
Native language of Flutter |
Not the primary Flutter language |
Native Android integration |
Native Android integration |
Native iOS integration |
37. Why Learn Dart Before Flutter?
Learning Dart fundamentals makes it easier to understand Flutter application code because Flutter interfaces and application logic are written using Dart.
Before starting advanced Flutter development, developers should understand:
- Variables and data types
- Operators
- Conditional statements
- Loops
- Functions
- Lists, Sets, and Maps
- Classes and objects
- Constructors
- Inheritance
- Polymorphism
- Abstraction
- Null safety
- Exception handling
- Future and async/await
- Streams
- JSON handling
38. Dart Learning Roadmap
- Introduction to Dart
- Variables and constants
- Data types
- Operators
- Conditional statements
- Loops
- Functions and parameters
- Collections
- Classes and objects
- Constructors
- Inheritance
- Polymorphism
- Abstraction
- Null safety
- Exception handling
- Asynchronous programming
- Future and async/await
- Streams
- JSON and API data
- Practical Dart projects
- Move from Dart fundamentals to Flutter development
39. Dart and Flutter Relationship
| Dart |
Flutter |
| Programming language |
UI/application development framework |
| Provides syntax and language features |
Provides widgets and application-development tools |
| Handles variables, functions and classes |
Uses Dart to create application interfaces and logic |
| Provides Future, async/await and Stream |
Uses asynchronous Dart programming for APIs and other operations |
| Provides collections such as List, Set and Map |
Uses collections throughout application development |
40. Key Takeaways
- Dart is the primary programming language used by Flutter.
- Dart is an object-oriented programming language.
- Dart supports variables, data types, functions, classes, inheritance, and abstraction.
- Dart provides collections such as List, Set, and Map.
- Dart includes null-safety features.
- Dart supports asynchronous programming using Future, async/await, and Stream.
- Dart can be used to process JSON and communicate with APIs in Flutter applications.
- Understanding Dart fundamentals is important before learning advanced Flutter development.
- Flutter uses Dart for both UI-related code and application logic.
- Learning Dart provides the programming foundation needed for Flutter development.
Conclusion
Dart is a modern programming language that forms the programming foundation of Flutter. Developers use Dart to create Flutter widgets, implement business logic, manage application state, communicate with APIs, process data, work with databases, and build complete mobile applications.
A strong understanding of Dart fundamentals—including variables, data types, functions, collections, OOP, null safety, exception handling, and asynchronous programming—helps developers progress effectively into Flutter development.
JustAcademy's Flutter curriculum includes a dedicated Dart Programming Fundamentals module covering variables, data types, operators, control statements, functions, object-oriented programming, classes, constructors, inheritance, polymorphism, abstraction, collections, and asynchronous programming. Explore JustAcademy's Flutter Training.
Learn Flutter with JustAcademy
Learn Dart and Flutter through practical training, coding exercises, API integration, Firebase, state management, projects, testing, deployment, and advanced Flutter concepts:
JustAcademy Flutter Training
Register for a course demo:
Register for Flutter Course Demo