Dart tutorial for Beginners
1. Hello, World!
Let's start with a classic "Hello, World!" example in Dart:
void main() {
print('Hello, World!');
}
- `void`: Specifies that the function doesn't return a value.
- `main()`: The entry point of the Dart program.
- `print()`: Outputs text to the console.
2. Variables and Data Types
Dart has a few basic data types:
void main() {
int age = 25;
double pi = 3.14159;
String name = 'John';
bool isStudent = true;
}
- `int`: Integer data type.
- `double`: Floating-point data type.
- `String`: Text data type.
- `bool`: Boolean data type.
3. Dynamic Typing
Dart is a dynamically typed language, meaning variable types are determined at runtime:
void main() {
var age = 25;
var name = 'John';
}
4. Constants
You can declare constants using the `final` and `const` keywords:
void main() {
final double pi = 3.14159;
const int daysInAWeek = 7;
}
- `final`: Can only be set once.
- `const`: Compile-time constant.
5. Basic Operators
Dart supports common operators like +, -, *, /, %, ==, !=, <, >, <=, >=:
void main() {
int x = 10;
int y = 5;
print(x + y); // 15
}
6. Control Structures
Dart supports if, else if, else, while, and for loops:
void main() {
int age = 18;
if (age < 18) {
print('You are a minor.');
} else {
print('You are an adult.');
}
}
7. Functions
Define and call functions in Dart:
void main() {
String greet(String name) {
return 'Hello, $name!';
}
print(greet('Alice')); // Hello, Alice!
}
8. Default Parameters
Set default values for function parameters:
void main() {
String greet(String name, [String prefix = 'Hello']) {
return '$prefix, $name!';
}
print(greet('Bob')); // Hello, Bob!
print(greet('Eve', 'Hi')); // Hi, Eve!
}
9. Named Parameters
Pass parameters by name:
void main() {
String greet({String name, String prefix = 'Hello'}) {
return '$prefix, $name!';
}
print(greet(name: 'Charlie')); // Hello, Charlie!
print(greet(prefix: 'Hi', name: 'Diana')); // Hi, Diana!
}
10. Lists
Create and manipulate lists:
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
numbers.add(6);
print(numbers); // [1, 2, 3, 4, 5, 6]
}
11. Maps
Work with key-value pairs using maps:
void main() {
Map<String, int> ages = {'Alice': 25, 'Bob': 30};
print(ages['Alice']); // 25
}
12. Classes and Objects
Define classes and create objects:
class Person {
String name;
int age;
Person(this.name, this.age);
}
void main() {
var person = Person('Emily', 28);
print(person.name); // Emily
}
13. Constructors
Use named constructors for better readability:
class Person {
String name;
int age;
Person(this.name, this.age);
Person.fromBirthYear(this.name, int birthYear) {
age = DateTime.now().year - birthYear;
}
}
void main() {
var person = Person.fromBirthYear('Frank', 1990);
print(person.age); // 33
}
14. Inheritance
Create a subclass that inherits from a superclass:
class Student extends Person {
String major;
Student(String name, int age, this.major) : super(name, age);
}
void main() {
var student = Student('Grace', 20, 'Computer Science');
print(student.major); // Computer Science
}
15. Getters and Setters
Define getters and setters for class properties:
class Circle {
double _radius;
Circle(this._radius);
double get radius => _radius;
set radius(double value) {
if (value > 0) {
_radius = value;
}
}
}
void main() {
var circle = Circle(5);
print(circle.radius); // 5.0
circle.radius = 7;
print(circle.radius); // 7.0
}
16. Abstract Classes and Interfaces
Create abstract classes and implement interfaces:
abstract class Shape {
double area();
}
class Circle implements Shape {
double radius;
Circle(this.radius);
@override
double area() => 3.14159 * radius * radius;
}
void main() {
var circle = Circle(5);
print(circle.area()); // 78.53975
}
17. Mixins
Use mixins to reuse code across classes:
mixin Logger {
void log(String message) {
print('Log: $message');
}
}
class Calculator with Logger {
int add(int a, int b) {
log('Adding $a and $b');
return a + b;
}
}
void main() {
var calc = Calculator();
print(calc.add(3, 5)); // 8
}
18. Exception Handling
Handle exceptions using try, catch, and finally:
void main() {
try {
var result = 10 ~/ 0; // Throws an exception
print(result);
} catch (e) {
print('Error: $e');
} finally {
print('Execution completed.');
}
}
19. Enums
Define custom data types using enums:
enum Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
void main() {
Day today = Day.Wednesday;
print(today); // Day.Wednesday
}
20. Asynchronous Programming
Use async and await for asynchronous operations:
Future<void> fetchUserData() async {
await Future.delayed(Duration(seconds: 2));
}