Dart is a programming language optimized for frontend applications such as web and mobile interfaces, focusing on rapid development and runtime performance.
It is widely used with Flutter to create cross-platform mobile applications.
Installation and Setup
Installation on Windows
Download the installer from dart.dev
Installation on Linux
sudo apt update -y
sudo apt install dartInstallation on macOS
brew tap dart-lang/dart
brew install dartVerify Installation
To check that Dart is correctly installed
dart --versionCompile and run a Dart file
To compile and run a .dart file:
dart run file.dartBasic Structure
Simple Program
The following code shows a basic program in Dart with the main function as the entry point.
void main() {
print('Hello, World!');
}Line Comment
// This is a single-line commentBlock Comment
/*
This is a comment
over multiple lines
*/Data Types
Primitive Types in Dart
Dart has several primitive data types: int, double, bool, String, and var.
| Type | Description | Example |
|---|---|---|
int | Integer | var a = 10; |
double | Decimal number | var b = 10.5; |
String | String of characters | var c = 'Hello'; |
bool | Boolean (true or false) | var d = true; |
dynamic | Can contain any type | var e; |
int integer = 42;
double decimal = 3.14;
bool isTrue = true;
String text = 'Hello';
var undefined = 'can be any type';Constants
In Dart, constants can be defined with const or final.
const: Value of the constant at compile time.final: Fixed value at runtime, but cannot be changed after initialization.
const double pi = 3.1416;
final DateTime now = DateTime.now();Null Safety
Dart has null safety to avoid null reference errors:
int? age; // Can be null
age = 20;
print(age);Operators
Dart includes several types of operators to perform operations with variables and constants.
Arithmetic Operators
+Addition-Subtraction*Multiplication/Division (returns adouble)~/Integer division (returns anint)%Modulo (remainder of the division)
int a = 10;
int b = 3;
print(a + b); // 13
print(a ~/ b); // 3
print(a % b); // 1Assignment Operators
=Assignment+=,-=,*=,/=,~/=,%=
int c = 5;
c += 2; // c = 7Relational Operators
==Equal to!=Not equal to>Greater than<Less than>=Greater than or equal to<=Less than or equal to
print(5 > 3); // trueLogical Operators
&&Logical AND||Logical OR!Logical NOT
bool isGreater = (5 > 3) && (2 < 4); // trueIncrement/Decrement Operator
++Increment by 1--Decrement by 1
int d = 5;
d++; // d = 6Null-aware Operator
??Returns the left value if it is notnull, otherwise returns the right value.
String? name;
print(name ?? 'No name'); // 'No name'Control Flow
Conditionals
if (condition) {
// code if the condition is true
} else if (otherCondition) {
// code if the other condition is true
} else {
// code if no condition is true
}Ternary Operator
var result = (condition) ? value1 : value2;Switch-case
switch (variable) {
case value1:
// code for value1
break;
case value2:
// code for value2
break;
default:
// code if there are no matches
}Loops
For Loop
for (int i = 0; i < 10; i++) {
print(i);
}While Loop
int i = 0;
while (i < 10) {
print(i);
i++;
}Do-while Loop
int i = 0;
do {
print(i);
i++;
} while (i < 10);Functions
Basic Function Definition
void printMessage(String message) {
print(message);
}Function with Return Value
int add(int a, int b) {
return a + b;
}Anonymous Functions
var anonymousFunction = () {
print('This is an anonymous function');
};Optional Parameters
In Dart, parameters can be optional or have default values:
- Named Parameters:
void greeting({String name = 'friend'}) {
print('Hello, $name');
}- Positional Parameters:
void showData(String name, [int age = 0]) {
print('Name: $name, Age: $age');
}Arrow Functions
Short functions can be expressed with arrows:
int multiply(int a, int b) => a * b;Functions as Parameters
void executeFunction(void Function() function) {
function();
}
void main() {
executeFunction(() => print('Function executed'));
}Closures
Function add(int a) {
return (int b) => a + b;
}
void main() {
var addWith5 = add(5);
print(addWith5(3)); // 8
}Collections
Lists
List Declaration
List<int> numbers = [1, 2, 3, 4, 5];Accessing Elements
print(list[0]); // Prints 1Common List Operations
numbers.add(6);
numbers.remove(3);
print(numbers.length);Sets
Set Declaration
Set<String> names = {'Ana', 'Luis', 'Carlos'};Set Operations
names.add('Pedro');
names.remove('Ana');Maps
Map Declaration
Map<String, int> ages = {'Luis': 25, 'Ana': 30};Accessing Values
print(ages['Luis']); // 25Classes and Objects
Class Definition
class Person {
String name;
int age;
Person(this.name, this.age);
void showData() {
print('Name: $name, Age: $age');
}
}Creating an Instance of a Class
void main() {
var person = Person('Luis', 25);
person.showData();
}Using Getters and Setters
class Circle {
double radius;
Circle(this.radius);
double get area => 3.1416 * radius * radius;
set changeRadius(double newRadius) => radius = newRadius;
}Named Constructors
class Person {
String name;
int age;
Person(this.name, this.age);
Person.withoutAge(this.name) {
age = 0;
}
}Inheritance
class Animal {
void sound() {
print('The animal makes a sound');
}
}
class Dog extends Animal {
@override
void sound() {
print('The dog barks');
}
}Static Methods
class Math {
static int add(int a, int b) {
return a + b;
}
}
void main() {
print(Math.add(5, 3));
}Asynchronous
Asynchronous Functions
Dart allows executing code asynchronously using Future and async/await.
Future<String> fetchData() async {
return 'Data fetched';
}
void main() async {
String result = await fetchData();
print(result);
}Simulating Delays
Future<void> simulateDelay() async {
await Future.delayed(Duration(seconds: 2));
print('Delay completed');
}Streams
Using Streams to Handle Data Flows
Stream<int> count() async* {
for (int i = 1; i <= 5; i++) {
yield i;
await Future.delayed(Duration(seconds: 1));
}
}
void main() async {
await for (var value in count()) {
print(value);
}
}Error Handling
Try-catch-finally
void main() {
try {
int result = 100 ~/ 0; // Division by zero
} catch (e) {
print('Error: $e');
} finally {
print('Operation completed');
}
}Throwing Exceptions
void validateAge(int age) {
if (age < 18) {
throw Exception('Invalid age');
}
}Packages and Dependency Management
Importing a Library
import 'dart:math';Creating a New Project
dart create my_projectManaging Dependencies with pubspec.yaml
In this file, you manage your project’s dependencies:
dependencies:
http: ^0.13.3To install the dependencies:
dart pub getUsing a Package
import 'package:http/http.dart' as http;
void main() async {
var response = await http.get(Uri.parse('https://example.com'));
print(response.body);
}