Introduction to Dart
Dart is a modern programming language developed by Google, optimized for creating cross-platform applications. Dart is the primary language used to develop Flutter applications.
⚙️ What is Dart?
Dart is a object-oriented, type-safe, and compiled programming language. Dart can be compiled to JavaScript for the web or native code for mobile and desktop.
💡 Why is Dart so important?
- Flutter - Primary language for Flutter development (mobile, web, desktop)
- Cross-platform - Single codebase for iOS, Android, Web, Windows, macOS, Linux
- Performance - Native compilation for optimal performance
- Hot Reload - Fast development with instant reload
- Google - Actively supported and developed by Google
- Growth - Rapid adoption in the mobile industry
🚀 Why learn Dart?
Dart is the language of the future for cross-platform development. Here's why you should learn Dart:
- ✅ Flutter - Development of native mobile applications with Flutter
- ✅ Cross-platform - Single code for all platforms
- ✅ Performance - Fast and smooth applications
- ✅ Modern UI - Creation of modern and attractive user interfaces
- ✅ Career - Strong demand for Flutter/Dart developers
- ✅ Ecosystem - Active community and rich libraries
📋 Prerequisites to learn Dart
To learn Dart effectively, it is recommended to have a foundation in programming (variables, conditions, loops).
- ✅ Programming basics - Understanding basic concepts (variables, conditions, loops)
- ✅ Object-oriented programming (optional) - Having OOP basics facilitates learning
- ✅ Flutter SDK - For developing Flutter applications
💡 Important note: To compile Dart code, you need the Dart SDK. Download it from the official Dart website. For Flutter, install Flutter SDK which includes Dart.
🎯 Dart Use Cases
Dart is used in many domains:
- 📱 Mobile applications - Flutter for iOS and Android
- 🌐 Web applications - Flutter Web for web applications
- 🖥️ Desktop applications - Flutter Desktop for Windows, macOS, Linux
- ⚡ High-performance applications - Native compilation for optimal performance
- 🔄 Hot Reload - Fast development with instant reload
- 📦 Cross-platform - Single codebase for all platforms
- 🎨 Modern UI - Creation of modern user interfaces
- 🚀 Rapid growth - Rapid adoption in the mobile industry
📝 Basic Syntax
Dart is a modern programming language. Dart uses braces {} to define code blocks and requires a semicolon ; at the end of each statement (optional but recommended).
// Premier programme C
#include
int main() {
printf("Bonjour, monde !\n");
return 0;
}
// Variables
int age = 25;
char nom[] = "NiangProgrammeur";
// Affichage formaté
printf("Je m'appelle %s et j'ai %d ans\n", nom, age);
// Opérations simples
int resultat = 10 + 5;
printf("10 + 5 = %d\n", resultat);
}
💡 Important points about Dart syntax:
- Dart uses braces
{}to define code blocks - Comments use
//for a single line or/* */for multiple lines - Semicolon optional but recommended
;at the end of each statement - Strings use single quotes
'or double quotes" - Each Dart program has a
main()function - Class names start with a capital letter (PascalCase convention)
🔍 Detailed syntax example
Here is a complete example showing several aspects of Dart syntax:
// Définition d'une fonction
double calculerMoyenne(List nombres) {
if (nombres.isEmpty) {
return 0;
}
int somme = 0;
for (int n in nombres) {
somme += n;
}
return somme / nombres.length;
}
// Fonction principale
void main() {
List notes = [15, 18, 12, 20, 16];
double moyenne = calculerMoyenne(notes);
print('La moyenne est : $moyenne');
}
🔤 Variables
In Dart, variables can be declared with an explicit type or with var (type inference). Dart is an optionally typed language.
#include
int main() {
// Déclaration de variables
int age = 30; // Entier
float prix = 19.99f; // Nombre décimal (simple précision)
double decimal = 3.14159; // Nombre décimal (double précision)
char lettre = 'A'; // Caractère unique
char nom[] = "C"; // Chaîne de caractères (tableau)
// Affichage avec printf
printf("Age: %d\n", age);
printf("Prix: %.2f\n", prix);
printf("Decimal: %lf\n", decimal);
printf("Lettre: %c\n", lettre);
printf("Nom: %s\n", nom);
// Déclaration puis assignation
int nombre;
nombre = 10;
printf("Nombre: %d\n", nombre);
// Constantes avec #define
#define PI 3.14159
#define MAX_SIZE 100
// Constantes avec const
const int TAILLE = 50;
const char* MESSAGE = "Bonjour";
// Noms de variables valides
int age_utilisateur = 25;
char nom_utilisateur[] = "Bassirou";
float _prive = 3.14; // Possible mais non recommandé
return 0;
}
📌 Règles pour les noms de variables :
- Doivent commencer par une lettre ou un underscore
_ - Peuvent contenir des lettres, chiffres et underscores
- Ne peuvent pas contenir d'espaces ou de caractères spéciaux
- Sont sensibles à la casse (
age≠Age) - Ne peuvent pas être des mots-clés Dart (
if,for,int,class, etc.) - Convention : utilisez
camelCasepour les variables locales,PascalCasepour les classes
📊 Data Types
Dart has several basic (primitive) data types. Here are the main types available in Dart:
#include
#include // Pour le type bool
int main() {
// Types entiers
char c = 'A'; // 1 octet (-128 à 127 ou 0 à 255)
short s = 100; // 2 octets (-32768 à 32767)
int i = 1000; // 4 octets (généralement)
long l = 100000L; // 4 ou 8 octets
long long ll = 1000000LL; // 8 octets
// Types entiers non signés
unsigned char uc = 200;
unsigned int ui = 5000;
unsigned long ul = 100000UL;
// Types décimaux
float f = 3.14f; // 4 octets (simple précision)
double d = 3.14159; // 8 octets (double précision)
long double ld = 3.141592653589793L; // 10 ou 16 octets
// Type booléen (C99+)
bool est_vrai = true;
bool est_faux = false;
// Chaînes de caractères (tableaux de char)
char chaine[] = "Hello"; // Tableau de caractères
char* pointeur = "World"; // Pointeur vers une chaîne
// Affichage avec printf
printf("char: %c\n", c);
printf("int: %d\n", i);
printf("float: %.2f\n", f);
printf("double: %lf\n", d);
printf("bool: %d\n", est_vrai);
printf("chaine: %s\n", chaine);
// Taille des types (en octets)
printf("Taille de int: %zu octets\n", sizeof(int));
printf("Taille de float: %zu octets\n", sizeof(float));
printf("Taille de double: %zu octets\n", sizeof(double));
return 0;
}
📚 Dart Data Types:
- int - Integer
- double - Decimal number
- String - Character string
- bool - Boolean (true/false)
- List - List (dynamic array)
- Map - Dictionary (key-value)
- Set - Set (unique values)
- dynamic - Dynamic type
- var - Type inference
🔢 Operators
Dart supports arithmetic, comparison, logical, assignment, and null-safety operators:
#include
#include // Pour pow()
int main() {
int a = 10, b = 3;
// Opérateurs arithmétiques
printf("%d + %d = %d\n", a, b, a + b); // Addition: 13
printf("%d - %d = %d\n", a, b, a - b); // Soustraction: 7
printf("%d * %d = %d\n", a, b, a * b); // Multiplication: 30
printf("%d / %d = %d\n", a, b, a / b); // Division entière: 3
printf("%d %% %d = %d\n", a, b, a % b); // Modulo (reste): 1
// Division avec float
float resultat = (float)a / b;
printf("%d / %d = %.2f\n", a, b, resultat); // Division: 3.33
// Puissance (nécessite math.h)
double puissance = pow(a, b);
printf("%d^%d = %.0f\n", a, b, puissance); // Puissance: 1000
// Opérateurs de comparaison
printf("%d > %d = %d\n", a, b, a > b); // 1 (true)
printf("%d < %d = %d\n", a, b, a < b); // 0 (false)
printf("%d >= %d = %d\n", a, b, a >= b); // 1 (true)
printf("%d <= %d = %d\n", a, b, a <= b); // 0 (false)
printf("%d == %d = %d\n", a, b, a == b); // 0 (false)
printf("%d != %d = %d\n", a, b, a != b); // 1 (true)
// Opérateurs logiques
int x = 1, y = 0; // 1 = true, 0 = false
printf("%d && %d = %d\n", x, y, x && y); // ET logique: 0
printf("%d || %d = %d\n", x, y, x || y); // OU logique: 1
printf("!%d = %d\n", x, !x); // NON logique: 0
// Opérateurs d'assignation
int c = 5;
c += 3; // Équivalent à c = c + 3 (c devient 8)
c -= 2; // Équivalent à c = c - 2 (c devient 6)
c *= 2; // Équivalent à c = c * 2 (c devient 12)
c /= 3; // Équivalent à c = c / 3 (c devient 4)
c %= 3; // Équivalent à c = c % 3 (c devient 1)
// Opérateurs d'incrémentation/décrémentation
int i = 5;
printf("i = %d\n", i++); // Post-incrémentation: affiche 5, puis i = 6
printf("i = %d\n", ++i); // Pré-incrémentation: i = 7, puis affiche 7
return 0;
}
🔀 Conditional Structures
The Dart language uses if, else if, and else for conditions. Code blocks are delimited by braces {}.
# Structure if simple
age = 20
if age >= 18:
print("Vous êtes majeur")
else:
print("Vous êtes mineur")
# Structure if/elif/else
age = 15
if age >= 18:
print("Vous êtes majeur")
print("Vous pouvez voter")
elif age >= 13:
print("Vous êtes adolescent")
elif age >= 6:
print("Vous êtes enfant")
else:
print("Vous êtes un bébé")
# Conditions multiples
note = 85
if note >= 90:
mention = "Excellent"
elif note >= 80:
mention = "Très bien"
elif note >= 70:
mention = "Bien"
elif note >= 60:
mention = "Assez bien"
else:
mention = "Insuffisant"
print(f"Votre mention : {mention}")
# Opérateur ternaire (expression conditionnelle)
age = 20
statut = "Majeur" if age >= 18 else "Mineur"
print(statut)
# Conditions avec and/or
age = 25
permis = True
if age >= 18 and permis:
print("Vous pouvez conduire")
else:
print("Vous ne pouvez pas conduire")
🔄 Loops
The Dart language offers several types of loops: for (to iterate a defined number of times), while (to repeat while a condition is true), do-while (executes at least once), and for-in (to iterate through collections):
# Boucle for avec range()
for i in range(5):
print(i) # Affiche 0, 1, 2, 3, 4
# range() avec début et fin
for i in range(1, 6):
print(i) # Affiche 1, 2, 3, 4, 5
# range() avec pas
for i in range(0, 10, 2):
print(i) # Affiche 0, 2, 4, 6, 8
# Boucle for avec liste
fruits = ["pomme", "banane", "orange"]
for fruit in fruits:
print(f"J'aime les {fruit}")
# Boucle for avec index (enumerate)
fruits = ["pomme", "banane", "orange"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Boucle while
compteur = 0
while compteur < 5:
print(compteur)
compteur += 1
# Boucle while avec break
compteur = 0
while True:
print(compteur)
compteur += 1
if compteur >= 5:
break # Sortir de la boucle
# continue (passer à l'itération suivante)
for i in range(10):
if i % 2 == 0: # Si i est pair
continue # Passer au suivant
print(i) # Affiche seulement les impairs: 1, 3, 5, 7, 9
# Boucle for avec else
for i in range(5):
print(i)
else:
print("Boucle terminée") # Exécuté si la boucle se termine normalement
⚙️ Functions
Functions allow code reuse. In Dart, we define a function with its return type (optional), name, and parameters. Functions can take parameters and return values with return.
# Fonction simple (sans paramètres)
def dire_bonjour():
print("Bonjour !")
dire_bonjour() # Appel de la fonction
# Fonction avec paramètres
def saluer(nom):
return f"Bonjour, {nom} !"
message = saluer("Python")
print(message) # "Bonjour, Python !"
# Fonction avec plusieurs paramètres
def additionner(a, b):
return a + b
resultat = additionner(5, 3)
print(resultat) # 8
# Fonction avec paramètres par défaut
def saluer_personne(nom, message="Bonjour"):
return f"{message}, {nom} !"
print(saluer_personne("Bassirou")) # "Bonjour, Bassirou !"
print(saluer_personne("Bassirou", "Salut")) # "Salut, Bassirou !"
# Fonction avec arguments nommés
def creer_personne(nom, age, ville="Dakar"):
return f"{nom}, {age} ans, habite à {ville}"
print(creer_personne("Bassirou", 25))
print(creer_personne(age=25, nom="Bassirou", ville="Thiès"))
# Fonction avec *args (arguments variables)
def additionner_nombres(*args):
return sum(args)
print(additionner_nombres(1, 2, 3, 4, 5)) # 15
# Fonction avec **kwargs (arguments nommés variables)
def afficher_info(**kwargs):
for cle, valeur in kwargs.items():
print(f"{cle}: {valeur}")
afficher_info(nom="Bassirou", age=25, ville="Dakar")
# Fonction lambda (fonction anonyme)
carre = lambda x: x ** 2
print(carre(5)) # 25
# Utilisation de lambda avec map()
nombres = [1, 2, 3, 4, 5]
carres = list(map(lambda x: x ** 2, nombres))
print(carres) # [1, 4, 9, 16, 25]
🏛️ Classes and Objects
In Dart, everything is object-oriented. Classes allow creating custom types with properties and methods.
// Définition d'une classe
class Personne {
// Propriétés
String nom;
int age;
double taille;
// Constructeur
Personne(this.nom, this.age, this.taille);
// Méthode
void afficher() {
print('Nom: $nom, Age: $age, Taille: ${taille}m');
}
}
void main() {
// Création d'objets
Personne p1 = Personne('Bassirou', 25, 1.75);
Personne p2 = Personne('Aminata', 30, 1.65);
p1.afficher();
p2.afficher();
}
🔀 Mixins
Mixins allow code reuse across multiple classes without inheritance.
// Définition d'un mixin
mixin Voler {
void voler() {
print('Je vole !');
}
}
mixin Nager {
void nager() {
print('Je nage !');
}
}
class Oiseau with Voler {
String nom;
Oiseau(this.nom);
}
class Canard with Voler, Nager {
String nom;
Canard(this.nom);
}
void main() {
Oiseau oiseau = Oiseau('Aigle');
oiseau.voler();
Canard canard = Canard('Colvert');
canard.voler();
canard.nager();
}
⚡ Futures and async/await
Dart supports asynchronous programming with Futures and async/await for non-blocking operations.
import 'dart:async';
// Fonction asynchrone
Future téléchargerDonnées() async {
await Future.delayed(Duration(seconds: 2));
return 'Données téléchargées';
}
void main() async {
print('Début du téléchargement...');
String données = await téléchargerDonnées();
print(données);
// Utilisation de then()
téléchargerDonnées().then((données) {
print('Avec then(): $données');
});
}
🌊 Streams
Streams allow managing asynchronous data sequences.
import 'dart:async';
Stream compter() async* {
for (int i = 1; i <= 5; i++) {
await Future.delayed(Duration(seconds: 1));
yield i;
}
}
void main() async {
await for (int nombre in compter()) {
print('Nombre: $nombre');
}
}
📱 Flutter - Introduction
Flutter uses Dart to create cross-platform applications with a single codebase.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Mon App',
home: Scaffold(
appBar: AppBar(
title: Text('Bienvenue'),
),
body: Center(
child: Text('Hello Flutter!'),
),
),
);
}
}
💡 Note importante : Dart utilise un garbage collector (GC) pour gérer automatiquement la mémoire. Vous n'avez pas besoin de libérer manuellement la mémoire comme en C/C++. Le GC s'occupe de libérer les objets non utilisés automatiquement.
🎓 Next Steps
Congratulations! You now have a solid foundation in Dart.
✅ What you have learned:
- Dart syntax and variables
- Data types (int, double, String, bool, List, Map)
- Operators (arithmetic, comparison, logical, null-safety)
- Conditional structures (if, else if, else, switch)
- Loops (for, while, do-while, for-in)
- Functions (definition, parameters, return, arrow functions)
- Classes and objects (encapsulation, constructors)
- Mixins and inheritance
- Futures and async/await
- Streams
- Flutter - Widgets and State Management
🚀 To go further:
- 📚 Advanced Flutter - Navigation, State Management, Animations
- 🔧 Dart packages - Using pub.dev packages
- 📦 Flutter Web - Web application development
- 🌐 Flutter Desktop - Cross-platform desktop applications
- 📊 State Management - Provider, Riverpod, Bloc
- 🤖 API and HTTP - REST API consumption