Dart Programming

Dart is a client-optimized language for fast apps on any platform. Developed by Google, it powers Flutter for beautiful native mobile, web, and desktop apps from a single codebase.

Why Learn Dart?

  • Optimized for UI development and fast execution
  • Power behind Flutter framework for cross-platform apps
  • Strong typing with sound null safety
  • Productive development with hot reload
  • Growing demand in mobile development market

Getting Started with Dart

Dart is a client-optimized programming language for apps on multiple platforms. It is developed by Google and is used to build mobile, desktop, server, and web applications.

Installation

Dart SDK can be installed on all major platforms:

Windows/macOS/Linux

  1. Download from dart.dev
  2. Run the installer
  3. Verify installation with:
  4. $ dart --version

Using Flutter

Dart comes bundled with Flutter. Install Flutter to get Dart:

$ flutter doctor

First Program

Create a file named hello.dart with this content:

// A simple Dart program
void main() {
  print('Hello, World!');
}

Run it from your terminal:

$ dart hello.dart

Dart Basics

Variables

// Variables with type annotation
String name = 'Alice'; // String
int age = 30; // Integer
double height = 5.9; // Double
bool isStudent = true; // Boolean
var inferred = 'Dart'; // Type inferred as String

Basic Operations

// Arithmetic operations
int x = 10 + 5; // Addition
int y = 10 * 5; // Multiplication

// String operations
String greeting = 'Hello' + ' ' + 'World';
String interpolated = 'Name: $name, Age: ${age + 1}';

Dart Topics

Comprehensive coverage of Dart programming concepts from beginner to advanced levels

Variables & Data Types

Learn about Dart's type system including strings, numbers, lists, maps, sets, and the dynamic type.

// Example of different data types
String name = 'Alice';
int age = 25;
List<double> prices = [10.5, 20.3, 15.0];
Map<String, dynamic> person = {'name': name, 'age': age};

Control Flow

Master if-else statements, switch-case, loops (for, while), and control flow in Dart.

// If-else example
if (age >= 18) {
  print('Adult');
} else {
  print('Minor');
}

// For loop
for (var i = 0; i < 5; i++) {
  print(i);
}

Functions

Learn to define and use functions, work with parameters, return values, and understand scope in Dart.

// Function definition
String greet(String name) {
  return 'Hello, $name!';
}

// Function with optional parameters
void log(String message, [String? level]) {
  final prefix = level ?? 'INFO';
  print('[$prefix] $message');
}

Lists & Maps

Work with Dart's powerful built-in collections for storing and organizing data.

// List and Map examples
List<String> fruits = ['apple', 'banana', 'cherry'];
Map<String, dynamic> person = {
  'name': 'Alice',
  'age': 25,
  'isStudent': true
};

// Accessing elements
var firstFruit = fruits[0];
var personAge = person['age'];

Loops & Iteration

Master for and while loops, collection methods, and iteration techniques in Dart.

// For loop examples
for (var fruit in fruits) {
  print(fruit);
}

// Collection methods
var lengths = fruits.map((fruit) => fruit.length).toList();
var filtered = fruits.where((fruit) => fruit.startsWith('a'));

Null Safety

Understand Dart's sound null safety and how to work with nullable types.

// Nullable vs non-nullable
String nonNullable = 'Dart'; // Can't be null
String? nullable; // Can be null

// Handling nulls
var length = nullable?.length ?? 0;
if (nullable != null) {
  var upper = nullable.toUpperCase();
}

Error Handling

Understand Dart's exception handling mechanism using try-catch blocks.

// Try-catch example
try {
  var result = 10 ~/ 0;
} on IntegerDivisionByZeroException {
  print('Cannot divide by zero');
} catch (e, stackTrace) {
  print('Error: $e');
  print('Stack trace: $stackTrace');
} finally {
  print('Operation complete');
}

Classes & Objects

Learn about classes, constructors, properties, methods, and object-oriented programming in Dart.

// Class definition
class Person {
  final String name;
  int age;

  Person(this.name, this.age);

  void sayHello() {
    print('Hello, I am $name');
  }
}

// Creating an object
var person = Person('Alice', 25);

Inheritance & Mixins

Understand class inheritance, interfaces, and mixins in Dart's object model.

// Inheritance example
class Animal {
  void eat() => print('Eating...');
}

class Dog extends Animal {
  void bark() => print('Barking...');
}

// Mixin example
mixin Swimmer {
  void swim() => print('Swimming...');
}

class Fish with Swimmer {}

Generics

Learn to use generics for type-safe collections and reusable code.

// Generic class example
class Box<T> {
  final T contents;

  Box(this.contents);

  T open() => contents;
}

// Using generic classes
var stringBox = Box<String>('Dart');
var intBox = Box<int>(42);

Futures & Async

Understand asynchronous programming with Futures, async, and await in Dart.

// Future example
Future<String> fetchUser() {
  return Future.delayed(
    Duration(seconds: 2),
    () => 'Alice'
  );
}

// Async/await example
Future<void> printUser() async {
  final user = await fetchUser();
  print(user);
}

Streams

Learn about Dart Streams for handling sequences of asynchronous events.

// Stream example
Stream<int> countStream(int max) async* {
  for (int i = 1; i <= max; i++) {
    await Future.delayed(Duration(seconds: 1));
    yield i;
  }
}

// Using the stream
void main() async {
  await for (final number in countStream(5)) {
    print(number);
  }
}

Extensions

Learn to add functionality to existing classes with Dart extension methods.

// Extension method example
extension NumberParsing on String {
  int toIntOrZero() {
    return int.tryParse(this) ?? 0;
  }
}

// Using the extension
void main() {
  var num = '42'.toIntOrZero();
  print(num); // 42
}

Isolates

Learn about Dart's concurrency model using isolates for parallel execution.

// Isolate example
void isolateFunction(SendPort sendPort) {
  final result = 'Message from isolate';
  sendPort.send(result);
}

Future<void> main() async {
  final receivePort = ReceivePort();
  await Isolate.spawn(isolateFunction, receivePort.sendPort);
  receivePort.listen((message) {
    print(message);
    receivePort.close();
  });
}

Testing

Learn to write unit tests for your Dart code using the test package.

// Simple test example
import 'package:test/test.dart';

int add(int a, int b) => a + b;

void main() {
  group('add function', () {
    test('adds two numbers', () {
      expect(add(2, 3), 5);
    });
  });
}

What Can You Build with Dart?

Dart's versatility makes it suitable for a wide range of applications across different platforms

Mobile Development

Build beautiful native apps using:

  • Flutter (Cross-platform)
  • Native performance
  • Single codebase for iOS/Android
// Simple Flutter app
import 'package:flutter/material.dart';

void main() => runApp(
  MaterialApp(
    home: Scaffold(
      body: Center(
        child: Text('Hello World!'),
      ),
    ),
  ),
);

Web Development

Build modern web applications with:

  • Flutter Web
  • AngularDart (Legacy)
  • Shelf (Backend)
// Simple Shelf server
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart';

void main() async {
  var handler = const Pipeline().addHandler((request) {
    return Response.ok('Hello, World!');
  });
  await serve(handler, 'localhost', 8080);
}

Desktop Applications

Build cross-platform desktop apps with:

  • Flutter Desktop
  • Native performance
  • Windows/macOS/Linux
// Flutter desktop window setup
void main() {
  runApp(MaterialApp(
    title: 'Desktop App',
    theme: ThemeData.dark(),
    home: Scaffold(
      appBar: AppBar(title: Text('Desktop App')),
    ),
  ));
}

Backend Development

Build server-side applications with:

  • Shelf (Middleware)
  • Aqueduct (Full framework)
  • gRPC support
// Simple HTTP server
import 'dart:io';

void main() async {
  final server = await HttpServer.bind('localhost', 8080);
  print('Server running on ${server.address}:${server.port}');
  await for (final request in server) {
    request.response.write('Hello, World!');
    await request.response.close();
  }
}

Command Line Tools

Build powerful CLI applications:

  • Args package
  • Console output formatting
  • File system operations
// Simple CLI tool
import 'dart:io';

void main(List<String> args) {
  if (args.isEmpty) {
    print('Usage: dart tool.dart <name>');
    exit(1);
  }
  print('Hello, ${args.first}!');
}

Game Development

Create games with Dart frameworks:

  • Flame (2D game engine)
  • Built on Flutter
  • Cross-platform
// Simple Flame game setup
import 'package:flame/game.dart';
import 'package:flutter/material.dart';

class MyGame extends FlameGame {
  @override
  Future<void> onLoad() async {
    // Game initialization
  }
}

void main() {
  runApp(GameWidget(game: MyGame()));
}

Dart Learning Path

A structured approach to mastering Dart programming

1 Beginner Level

  • Dart Syntax and Basics

    Variables, data types, operators, and basic I/O

  • Control Flow

    Conditionals, loops, and exception handling

  • Functions and Null Safety

    Defining functions, working with nullable types

  • Collections

    Lists, Maps, Sets, and basic operations

2 Intermediate Level

  • Object-Oriented Programming

    Classes, constructors, inheritance, and mixins

  • Advanced Collections

    Iterables, collection methods, and generics

  • Asynchronous Programming

    Futures, async/await, and error handling

  • Working with Packages

    Pub package manager, importing libraries

3 Advanced Level

  • Streams and Reactive Programming

    Working with Streams and StreamControllers

  • Isolates and Concurrency

    Parallel execution with isolates

  • Extensions and Metaprogramming

    Adding functionality to existing classes

  • Performance Optimization

    Benchmarking and optimizing Dart code

Ready to Master Dart?

Join our Dart & Flutter Mastery course and get access to interactive exercises, real-world projects, and expert support to accelerate your learning.