Dart Basics
Learn the Dart programming language fundamentals
🎯 Introduction to Dart
Dart is a modern, object-oriented programming language developed by Google. It's easy to learn with familiar syntax, supports strong typing, and powers Flutter applications with excellent performance and developer productivity.
// Your first Dart program
void main() {
print('Hello, Dart!');
var name = 'Flutter';
var year = 2024;
print('Welcome to $name in $year');
}
Output:
Hello, Dart! Welcome to Flutter in 2024
Dart Fundamentals
Variables
Store and manage data
var name = 'John';
int age = 25;
String city = 'NYC';
Data Types
Different kinds of values
int, double
String, bool
List, Map
Functions
Reusable code blocks
void greet() {
print('Hi!');
}
Classes
Object-oriented programming
class Person {
String name;
}
🔹 Variables and Data Types
Declaring and using variables in Dart:
🔸 Variable Declaration
// Using var (type inference)
var name = 'Alice'; // String
var age = 30; // int
var height = 5.8; // double
var isStudent = true; // bool
// Explicit type declaration
String city = 'New York';
int year = 2024;
double price = 99.99;
bool isActive = false;
// Final (runtime constant)
final currentDate = DateTime.now();
// Const (compile-time constant)
const pi = 3.14159;
void main() {
print('Name: $name');
print('Age: $age');
print('City: $city');
}
Output:
Name: Alice Age: 30 City: New York
🔹 Basic Data Types
Common data types in Dart:
void main() {
// Numbers
int count = 42; // Integer
double temperature = 98.6; // Decimal
num value = 100; // Can be int or double
// Strings
String greeting = 'Hello';
String name = "Dart";
String message = '''
Multi-line
string
''';
// Booleans
bool isTrue = true;
bool isFalse = false;
// Lists (Arrays)
List<int> numbers = [1, 2, 3, 4, 5];
var fruits = ['Apple', 'Banana', 'Orange'];
// Maps (Key-Value pairs)
Map<String, int> ages = {
'Alice': 25,
'Bob': 30,
};
// Print examples
print('Count: $count');
print('First fruit: ${fruits[0]}');
print('Alice age: ${ages['Alice']}');
}
Output:
Count: 42 First fruit: Apple Alice age: 25
🔹 Functions
Creating and using functions:
// Basic function
void greet() {
print('Hello!');
}
// Function with parameters
void sayHello(String name) {
print('Hello, $name!');
}
// Function with return value
int add(int a, int b) {
return a + b;
}
// Arrow function (short syntax)
int multiply(int a, int b) => a * b;
// Optional parameters
void introduce(String name, [int? age]) {
print('Name: $name');
if (age != null) {
print('Age: $age');
}
}
// Named parameters
void createUser({required String name, int age = 18}) {
print('User: $name, Age: $age');
}
void main() {
greet();
sayHello('Alice');
var sum = add(5, 3);
print('Sum: $sum');
var product = multiply(4, 5);
print('Product: $product');
introduce('Bob', 25);
createUser(name: 'Charlie');
}
Output:
Hello! Hello, Alice! Sum: 8 Product: 20 Name: Bob Age: 25 User: Charlie, Age: 18
🔹 Control Flow
If statements, loops, and conditions:
void main() {
// If-else statement
int age = 20;
if (age >= 18) {
print('Adult');
} else {
print('Minor');
}
// For loop
for (int i = 1; i <= 3; i++) {
print('Count: $i');
}
// For-in loop
var fruits = ['Apple', 'Banana', 'Orange'];
for (var fruit in fruits) {
print(fruit);
}
// While loop
int count = 0;
while (count < 3) {
print('While: $count');
count++;
}
// Switch statement
var grade = 'A';
switch (grade) {
case 'A':
print('Excellent!');
break;
case 'B':
print('Good!');
break;
default:
print('Keep trying!');
}
}
Output:
Adult Count: 1 Count: 2 Count: 3 Apple Banana Orange While: 0 While: 1 While: 2 Excellent!
🔹 Classes and Objects
Object-oriented programming in Dart:
// Define a class
class Person {
// Properties
String name;
int age;
// Constructor
Person(this.name, this.age);
// Method
void introduce() {
print('Hi, I am $name and I am $age years old.');
}
// Getter
bool get isAdult => age >= 18;
}
// Class with named constructor
class User {
String username;
String email;
User(this.username, this.email);
// Named constructor
User.guest() : username = 'Guest', email = '[email protected]';
}
void main() {
// Create objects
var person1 = Person('Alice', 25);
person1.introduce();
print('Is adult: ${person1.isAdult}');
var person2 = Person('Bob', 16);
person2.introduce();
print('Is adult: ${person2.isAdult}');
var user = User.guest();
print('Username: ${user.username}');
}
Output:
Hi, I am Alice and I am 25 years old. Is adult: true Hi, I am Bob and I am 16 years old. Is adult: false Username: Guest
🔹 Lists and Collections
Working with lists and maps:
void main() {
// Lists
List<String> fruits = ['Apple', 'Banana', 'Orange'];
// Add items
fruits.add('Mango');
// Access items
print('First: ${fruits[0]}');
print('Length: ${fruits.length}');
// Loop through list
for (var fruit in fruits) {
print(fruit);
}
// List methods
fruits.remove('Banana');
print('Contains Apple: ${fruits.contains('Apple')}');
// Maps
Map<String, int> scores = {
'Alice': 95,
'Bob': 87,
'Charlie': 92,
};
// Access map values
print('Alice score: ${scores['Alice']}');
// Add to map
scores['David'] = 88;
// Loop through map
scores.forEach((name, score) {
print('$name: $score');
});
}
Output:
First: Apple Length: 4 Apple Banana Orange Mango Contains Apple: true Alice score: 95 Alice: 95 Bob: 87 Charlie: 92 David: 88
🔹 Null Safety
Dart's null safety features:
void main() {
// Non-nullable variable (cannot be null)
String name = 'Alice';
// name = null; // Error!
// Nullable variable (can be null)
String? nickname = null;
nickname = 'Ally';
// Null-aware operators
String? username;
// ?? operator (default value if null)
String displayName = username ?? 'Guest';
print('Display: $displayName');
// ?. operator (safe navigation)
print('Length: ${username?.length}');
// ! operator (assert non-null)
String? confirmedName = 'Bob';
String definite = confirmedName!;
print('Definite: $definite');
// Late variables
late String description;
description = 'Initialized later';
print(description);
}
Output:
Display: Guest Length: null Definite: Bob Initialized later
🔹 Dart for Flutter
How Dart concepts apply to Flutter:
import 'package:flutter/material.dart';
// Classes for widgets
class MyButton extends StatelessWidget {
final String text;
final VoidCallback onPressed;
// Constructor with named parameters
MyButton({required this.text, required this.onPressed});
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed,
child: Text(text),
);
}
}
// Using the widget
void main() {
runApp(
MaterialApp(
home: Scaffold(
body: Center(
child: MyButton(
text: 'Click Me',
onPressed: () {
print('Button clicked!');
},
),
),
),
),
);
}