- Introduction to Dart
- Dart Basics
- Control Structures
- Functions
- Classes and Objects
- Collections (Lists, Sets, and Maps)
- Asynchronous Programming
- Error Handling
- Null Safety
- Dart Packages and Libraries
- File I/O and HTTP Requests
- Regular Expressions
- Miscellaneous Concepts
- Definition: Dart is an open-source, general-purpose programming language developed by Google. It is optimized for building user interfaces and powers frameworks like Flutter for mobile, web, and desktop applications.
- History: First released in 2011, Dart has grown significantly and is now used to build fast and scalable apps.
- Execution: Dart code can be compiled to native machine code or JavaScript for web applications.
- Declaring Variables:
var
: Type inference, can hold any type.dynamic
: Allows a variable to change its type during runtime.final
: Variable can be set only once.const
: Compile-time constant.
var name = 'John'; // Type inferred as String
dynamic age = 30; // Can change type later
final city = 'New York'; // Immutable after assignment
const pi = 3.14; // Compile-time constant
- Primitive Data Types:
- int: Integer numbers (e.g.,
42
) - double: Floating-point numbers (e.g.,
3.14
) - String: Text data (e.g.,
'Hello'
) - bool: Boolean values (
true
orfalse
) - List: Ordered collection of items (array)
- Map: Key-value pairs
- int: Integer numbers (e.g.,
int age = 25;
double height = 5.9;
String greeting = 'Hello, World!';
bool isAdult = true;
List<int> numbers = [1, 2, 3];
Map<String, String> user = {'name': 'Alice', 'city': 'London'};
- Arithmetic Operators:
+
,-
,*
,/
,%
- Assignment Operators:
=
,+=
,-=
,*=
,/=
,%=
- Comparison Operators:
==
,!=
,>
,<
,>=
,<=
- Logical Operators:
&&
(and),||
(or),!
(not)
int sum = 5 + 3;
bool isEqual = (5 == 5); // true
bool isAdult = (age >= 18) && (isStudent == false);
- if/else
if (age >= 18) {
print('You are an adult.');
} else {
print('You are not an adult.');
}
- switch/case
String fruit = 'apple';
switch (fruit) {
case 'banana':
print('Banana is yellow.');
break;
case 'apple':
print('Apple is red.');
break;
default:
print('Unknown fruit.');
}
- for loop
for (int i = 0; i < 5; i++) {
print(i);
}
- while loop
int count = 0;
while (count < 5) {
print(count);
count++;
}
- do...while loop
int number = 0;
do {
print(number);
number++;
} while (number < 5);
- for...in loop
List<int> numbers = [1, 2, 3];
for (int num in numbers) {
print(num);
}
void greet(String name) {
print('Hello, $name!');
}
greet('Alice'); // Outputs: Hello, Alice!
var greet = (String name) => 'Hello, $name!';
print(greet('Bob')); // Outputs: Hello, Bob!
void greet(String name, [String? title]) {
print('Hello, ${title ?? ''} $name!');
}
greet('Alice');
greet('Alice', 'Dr.');
void greet({required String name, String? title}) {
print('Hello, ${title ?? ''} $name!');
}
greet(name: 'Alice', title: 'Dr.');
class Person {
String name;
int age;
Person(this.name, this.age);
void greet() {
print('Hello, my name is $name and I am $age years old.');
}
}
Person alice = Person('Alice', 30);
alice.greet(); // Outputs: Hello, my name is Alice and I am 30 years old.
class Animal {
void sound() {
print('Animal makes a sound');
}
}
class Dog extends Animal {
@override
void sound() {
print('Dog barks');
}
}
Dog dog = Dog();
dog.sound(); // Outputs: Dog barks
List<String> fruits = ['apple', 'banana', 'cherry'];
fruits.add('date');
print(fruits);
Set<int> numbers = {1, 2, 3, 4};
numbers.add(5);
print(numbers);
Map<String, String> user = {'name': 'Alice', 'city': 'Wonderland'};
user['country'] = 'Wonderland';
print(user);
Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 2));
return 'Data received';
}
fetchData().then((data) => print(data));
Future<void> fetchData() async {
try {
String data = await Future.delayed(Duration(seconds: 2), () => 'Data received');
print(data);
} catch (e) {
print('Error: $e');
}
}
fetchData();
try {
int result = 100 ~/ 0;
print(result);
} catch (e) {
print('Error: $e');
} finally {
print('Execution completed.');
}
Dart introduced null safety to eliminate null reference errors, a common source of bugs. Null safety ensures that variables cannot be null unless explicitly declared as nullable.
int a = 10; // Non-nullable
int? b; // Nullable
Use !
to assert that a nullable variable is not null.
int? a;
int b = a!; // Throws error if a is null
??
: Provides a default value if a variable is null.?.
: Calls a method or accesses a property only if the variable is not null.
int? age;
print(age ?? 18); // Outputs: 18
String? name;
print(name?.toUpperCase()); // Outputs: null
Dart has a rich ecosystem of packages and libraries that can be used to enhance your projects. The main package manager is pub.dev.
- Find a package on pub.dev.
- Add the package to your
pubspec.yaml
file. - Run
dart pub get
to install the package. - Import the package into your Dart file.
# pubspec.yaml
name: my_app
dependencies:
http: ^0.13.4
// main.dart
import 'package:http/http.dart' as http;
dart create my_package
import 'dart:io';
void writeFile() {
File file = File('example.txt');
file.writeAsStringSync('Hello, Dart!');
}
void readFile() {
File file = File('example.txt');
String content = file.readAsStringSync();
print(content);
}
import 'package:http/http.dart' as http;
Future<void> fetchData() async {
var url = Uri.parse('https://jsonplaceholder.typicode.com/posts/1');
var response = await http.get(url);
if (response.statusCode == 200) {
print(response.body);
} else {
print('Request failed with status: ${response.statusCode}.');
}
}
Dart provides robust support for regular expressions through the RegExp class.
RegExp regExp = RegExp(r'^[a-zA-Z0-9]+$');
String input = 'Dart123';
print(regExp.hasMatch(input)); // true
RegExp regExp = RegExp(r'Dart');
String input = 'I love Dart programming.';
print(input.replaceAll(regExp, 'Flutter')); // I love Flutter programming.
List<int> numbers = [1, 2, 3];
Map<String, int> nameAgeMap = {'Alice': 30, 'Bob': 25};
dynamic value = 'Hello';
String message = value as String;
print(message);
enum Color { red, green, blue }
void main() {
Color favoriteColor = Color.blue;
print(favoriteColor);
}