🚀 Dart Introduction

🎯 Complete Definition

Dart is a client-optimized, garbage-collected, object-oriented programming language for fast apps on any platform. Developed by Google and first released in 2011, Dart is the foundation of Flutter, enabling natively compiled applications for mobile, desktop, and web from a single codebase. It combines the productivity of a high-level language with performance of native compilation (AOT) and developer convenience of JIT (with hot reload).

🔬 Core Characteristics

  • Optimized for UI: Great for building mobile, desktop, and web user interfaces (Flutter).
  • Compiled: Both AOT (ahead-of-time) for production and JIT (just-in-time) for development.
  • Sound null safety: Variables are non-nullable by default (since Dart 2.12).
  • Object-oriented: Everything is an object, all classes inherit from Object.
  • Strong typing: Optional, type-safe with type inference (var, final).
  • Multi-paradigm: Supports functional programming (closures, higher-order functions).
  • Isolates for concurrency: Memory-isolated workers (no shared memory threads).
  • Rich standard library: Core, async, math, io, collections, and more.

📊 Industry Usage

Dart is the language behind Flutter, which powers apps from Google, Alibaba, eBay, BMW, and thousands of startups. Flutter is used for cross-platform mobile, web, and desktop apps. Dart is also used for server-side (Dart Frog, Shelf) and IoT applications. With growing adoption, Dart is a top 20 language (RedMonk, GitHub).

void main() { print('🎯 Dart 3.4 - CodeOrbitPro Pro Track'); var name = 'Dart'; int year = 2011; final isAwesome = true; print('$name was created in $year. Awesome: $isAwesome'); // Sound null safety - non-nullable by default String language = 'Dart'; // cannot be null // String? nullable = null; // Nullable with ? }

📊 Basics & Syntax

🎯 Complete Definition

Dart syntax is C-style, familiar to Java, JavaScript, C# developers. Every app has a main() function as entry point. Statements end with semicolons. Blocks use curly braces. Comments: //, /* */, /// (documentation). Dart supports top-level functions and variables.

🏗️ Basic Syntax Rules

  • Entry point: void main() { ... }
  • Printing: print('Hello');
  • Variables: var name = 'value'; (type inferred), or explicit String name = 'value';
  • Constants: final (set once), const (compile-time constant).
  • String interpolation: 'Hello $name' or '${expression}'.
  • Comments: //, /* */, /// (doc comments).
/// This is a documentation comment for the main function void main() { // This is a single-line comment /* This is a multi-line comment */ var message = 'Hello, Dart!'; String explicit = 'Type annotation'; final language = 'Dart'; // can't be reassigned const pi = 3.14159; // compile-time constant int? nullableInt; // initialized to null by default (if nullable) print(message); print('I am learning $language'); print('Pi rounded: ${pi.toStringAsFixed(2)}'); }

📦 Variables & Types

🎯 Complete Definition

Dart is statically typed with type inference. Built-in types: int, double, num, String, bool, List, Set, Map, Runes, Symbol, and Null. All types are objects; even int and bool have methods. Sound null safety means types are non-nullable by default; add ? for nullability.

🔤 Core Types

  • Numbers: int (platform-dependent, up to 64-bit), double (64-bit floating point), num (supertype).
  • Strings: String (UTF-16), immutable. Single or double quotes, triple quotes for multiline.
  • Booleans: booltrue or false.
  • Lists: List<T> (array).
  • Sets: Set<T> (unordered unique).
  • Maps: Map<K,V> (key-value).
  • Runes: Unicode code points.
  • Symbols: Opaque name identifiers.
void main() { // Numbers int age = 25; double height = 1.85; num x = 10; // can be int or double // String String name = 'Dart'; String multiline = ''' This is a multiline string '''; // Boolean bool isFun = true; // Type checking print(age is int); // true print(height.runtimeType); // double // Null safety String? nullableName; // can be null nullableName = 'Bob'; // String nonNullable = null; // Error! // Type conversion int parsed = int.parse('42'); double pi = 3.14159; String piStr = pi.toStringAsFixed(2); }

🔢 Operators

🎯 Complete Definition

Operators in Dart are similar to Java/C. They can be overloaded. Important: type test operators (is, is!), as (cast), assignment, null-aware operators (??, ??=, ?.), cascade (..) for chaining, and spread operators (..., ...?) for collections.

📋 Operator Categories

  • Arithmetic: +, -, *, /, ~/ (integer division), %, -expr (unary minus).
  • Assignment: =, +=, -=, etc., and ??= (assign if null).
  • Comparison: ==, !=, >, <, >=, <=.
  • Type test: as (cast), is, is!.
  • Logical: !, &&, ||.
  • Bitwise: &, |, ^, ~expr, <<, >>, >>>.
  • Conditional: expr1 ? expr2 : expr3, ?? (if null).
  • Cascade: .. allows multiple operations on same object.
  • Spread: ... (expand collection), ...? (null-aware).
void main() { // Arithmetic int a = 10, b = 3; print(a + b); // 13 print(a ~/ b); // 3 (integer division) // Null-aware String? name; String displayName = name ?? 'Guest'; // 'Guest' name ??= 'New Name'; // assigns if null // Cascade var list = [] ..add(1) ..add(2) ..remove(1); print(list); // [2] // Type test var value = 'hello'; if (value is String) { print(value.toUpperCase()); // HELLO } // Spread var list2 = [0, ...list, 3]; print(list2); // [0, 2, 3] }

🔀 Control Flow

🎯 Complete Definition

Control flow statements include if/else, for loops, while, do-while, switch, and assert. Dart also has break, continue. Switch supports patterns (Dart 3) for destructuring and type matching.

🏗️ Control Structures

  • if/else: standard.
  • for: for (int i = 0; i < 5; i++) and for (var item in list).
  • while / do-while.
  • switch: with patterns (Dart 3).
  • assert: assert(condition, 'message'); only in debug.
void main() { int score = 85; // if/else if (score >= 90) { print('A'); } else if (score >= 80) { print('B'); // prints B } else { print('C'); } // for loop for (int i = 0; i < 3; i++) { print(i); // 0,1,2 } var items = ['Dart', 'Flutter']; for (var item in items) { print(item); } // while int count = 0; while (count < 3) { print('count: $count'); count++; } // switch with patterns (Dart 3) var pair = (1, 'one'); switch (pair) { case (1, 'one'): print('Found one'); break; default: print('Unknown'); } // assert (debug only) // assert(score > 0, 'Score must be positive'); }

⚙️ Functions

🎯 Complete Definition

Functions are first-class objects. They can be assigned to variables, passed as arguments. Dart supports named parameters (required or optional), positional optional parameters, arrow syntax (=>) for single expressions, and lexical closures.

⚙️ Function Features

  • Positional required: int add(int a, int b) => a + b;
  • Optional positional: String greet(String name, [String title = '']) { ... }
  • Named parameters: void build({required String name, int age = 0})
  • Anonymous functions: var square = (int x) => x * x;
  • Lexical closures: functions capture surrounding variables.
  • Return type: Can be omitted (dynamic), but best practice to specify.
// Arrow syntax (single expression) int square(int x) => x * x; // Named parameters with required void greet({required String name, int age = 0}) { print('Hello $name, age $age'); } // Optional positional String joinWith(String a, String b, [String separator = ' ']) { return '$a$separator$b'; } // Function as first-class void applyFunction(List list, int Function(int) func) { for (var i = 0; i < list.length; i++) { list[i] = func(list[i]); } } void main() { print(square(5)); // 25 greet(name: 'Alice', age: 30); // Hello Alice, age 30 print(joinWith('Hello', 'World')); // Hello World print(joinWith('Hello', 'World', ',')); // Hello,World // Anonymous function var list = [1, 2, 3]; applyFunction(list, (x) => x * 2); print(list); // [2,4,6] // Closure Function makeAdder(int addBy) { return (int i) => i + addBy; } var add2 = makeAdder(2); print(add2(3)); // 5 }

📋 Collections

🎯 Complete Definition

Collections are core data structures: List (ordered, indexable), Set (unordered, unique), Map (key-value). All are generic and growable by default. Dart offers collection literals and spread operators.

📊 Collection Operations

  • List: [], List.filled(), .length, .add(), .remove(), .map(), .where(), .first, .last.
  • Set: {}, .add(), .contains(), .union(), .intersection().
  • Map: {'key': 'value'}, .keys, .values, .putIfAbsent(), .update().
void main() { // List var fruits = ['apple', 'banana', 'orange']; fruits.add('kiwi'); print(fruits[1]); // banana print(fruits.length); // 4 // List with type List numbers = [1, 2, 3]; var doubled = numbers.map((n) => n * 2).toList(); // [2,4,6] // Set var unique = {1, 2, 3, 1}; // {1,2,3} unique.add(4); print(unique.contains(2)); // true // Map var scores = {'Alice': 95, 'Bob': 87}; scores['Charlie'] = 92; print(scores['Alice']); // 95 // Iteration fruits.forEach((f) => print(f)); // Spread var moreFruits = ['mango', ...fruits]; var withNull = [...?maybeList]; // null-aware spread }

📝 Strings

🎯 Complete Definition

Strings are immutable sequences of UTF-16 code units. They support interpolation, concatenation, multiline literals (triple quotes), and raw strings (r'...'). The String class provides many methods: toLowerCase(), substring(), split(), trim(), contains(), replaceAll().

🔤 String Operations

  • Interpolation: 'Hello $name, your score is ${score}'.
  • Concatenation: str1 + str2 or adjacent string literals 'Hello' 'World'.
  • Multiline: ''' ... ''' or """ ... """.
  • Raw string: r'C:\path\to\file' (no escapes).
  • Methods: .length, .isEmpty, .toUpperCase(), .indexOf(), .startsWith().
void main() { String name = 'Dart'; int version = 3; // Interpolation print('Learning $name version $version'); print('Sum of 2+3 = ${2+3}'); // Multiline String multiline = ''' This is a multiline string '''; // Raw string String path = r'C:\Program Files\Dart'; // Methods String text = ' Hello, Dart! '; print(text.trim()); // 'Hello, Dart!' print(text.toLowerCase()); // ' hello, dart! ' print(text.contains('Dart')); // true List parts = 'one,two,three'.split(','); print(parts); // [one, two, three] // Build string efficiently var buffer = StringBuffer(); buffer.write('Hello'); buffer.writeAll([' ', 'World', '!']); print(buffer.toString()); // Hello World! }

🏗️ Classes & OOP

🎯 Complete Definition

Dart is a pure object-oriented language with classes and single inheritance. Every class implicitly defines an interface. Features: constructors (generative, named, factory), initializer lists, getters/setters, static members, and late variables.

🏛️ Class Features

  • Constructor: ClassName(this.field1, this.field2);
  • Named constructor: ClassName.named() { ... }
  • Factory constructor: factory ClassName() { ... } (can return subtype).
  • Getters/Setters: Type get field => _field;
  • Initializer list: ClassName() : _field = value, super() { ... }
  • late: Non-nullable variable initialized later.
  • Static: static const, static method().
class Person { // Fields String name; int _age; // private (library-private) // Constructor with initializer list Person(this.name, int age) : _age = age { print('Person created'); } // Named constructor Person.guest() : name = 'Guest', _age = 0; // Getter int get age => _age; // Setter set age(int value) { if (value >= 0) _age = value; } // Method void introduce() { print('Hi, I\'m $name, age $_age'); } // Static static String species = 'Homo sapiens'; static void info() => print('We are $species'); } void main() { var alice = Person('Alice', 30); alice.introduce(); var guest = Person.guest(); guest.age = 25; // using setter print(guest.age); // 25 Person.info(); // static call }

🔗 Inheritance & Mixins

🎯 Complete Definition

Inheritance: Single inheritance via extends. Subclass can override methods, use super. Mixins are a way to reuse code in multiple class hierarchies (mixin keyword). Use with to apply mixins. Also implements for interfaces (all methods must be overridden).

🔗 Key Concepts

  • extends: Single inheritance.
  • implements: Treat class as interface.
  • with: Mix in mixins.
  • abstract class: Cannot be instantiated, may contain abstract methods.
  • @override: Annotation to indicate overriding.
  • super: Reference to parent.
abstract class Animal { void makeSound(); // abstract method void breathe() => print('Breathing'); } mixin Flyable { void fly() => print('Flying'); } mixin Swimmable { void swim() => print('Swimming'); } class Bird extends Animal with Flyable { @override void makeSound() => print('Chirp'); } class Duck extends Animal with Flyable, Swimmable { @override void makeSound() => print('Quack'); } class Dog extends Animal { @override void makeSound() => print('Bark'); } void main() { var bird = Bird(); bird.makeSound(); // Chirp bird.fly(); // Flying bird.breathe(); // Breathing var duck = Duck(); duck.swim(); // Swimming }

⚡ Async & Futures

🎯 Complete Definition

Asynchronous programming in Dart uses Future and async/await. A Future represents a potential value or error in the future. async marks a function that returns a Future. await pauses until the future completes. Stream provides asynchronous sequence of data.

⚙️ Async Patterns

  • Future: Future<T> – eventually produces T or error.
  • async/await: Write async code like synchronous.
  • then/catchError: Callback style (avoid if using await).
  • Stream: Sequence of async events. Use await for or listen().
  • Isolate: For parallel computation (separate memory).
import 'dart:async'; Future fetchData() async { // Simulate network delay await Future.delayed(Duration(seconds: 2)); return 'Data loaded'; } Future process() async { print('Start'); try { String result = await fetchData(); print(result); } catch (e) { print('Error: $e'); } print('End'); } // Stream example Stream countStream(int max) async* { for (int i = 1; i <= max; i++) { await Future.delayed(Duration(seconds: 1)); yield i; // emit value } } void main() async { await process(); // Consume stream await for (int value in countStream(3)) { print('Stream: $value'); } // Future.wait var futures = [fetchData(), fetchData()]; var results = await Future.wait(futures); print(results); }

🛡️ Exceptions

🎯 Complete Definition

Exceptions are errors that occur during execution. Dart provides Exception and Error types. Use throw to raise, try/catch/finally to handle. catch can have on for specific types. rethrow propagates caught exception.

⚠️ Exception Handling

  • throw: throw Exception('message');
  • try / on / catch / finally: standard.
  • rethrow: preserve stack trace.
  • Custom exceptions: implement Exception interface.
class CustomException implements Exception { final String message; CustomException(this.message); @override String toString() => 'CustomException: $message'; } void riskyFunction(int value) { if (value < 0) { throw CustomException('Value cannot be negative'); } if (value == 0) { throw 'Zero not allowed'; // can throw any object } print('Value is $value'); } void main() { try { riskyFunction(-5); } on CustomException catch (e, stackTrace) { print('Caught custom: $e'); print('Stack trace: $stackTrace'); } on String catch (msg) { print('String error: $msg'); } catch (e) { print('Unknown error: $e'); } finally { print('Cleanup (always runs)'); } // Rethrow example try { try { throw Exception('inner'); } catch (e) { print('Caught, rethrowing'); rethrow; } } catch (e) { print('Final handler: $e'); } }

📦 Generics

🎯 Complete Definition

Generics allow types to be parameterized, improving type safety and code reuse. Used in collections (List<String>), classes, methods. Type parameters can have bounds (T extends SomeType). Dart uses reified generics (type info retained at runtime).

🔧 Generic Usage

  • Generic class: class Box<T> { T value; }
  • Generic method: T first<T>(List<T> list) => list[0];
  • Type bounds: T extends num
  • Collection literals: var list = <int>[];
// Generic class class Pair { final A first; final B second; Pair(this.first, this.second); @override String toString() => '($first, $second)'; } // Generic method with bound T max(T a, T b) { return a > b ? a : b; } // Generic function type alias typedef Transformer = T Function(T input); void main() { var pair = Pair('age', 30); print(pair); // (age, 30) var numbers = [1, 2, 3]; print(max(10, 20)); // 20 // print(max('a', 'b')); // Error: String not num // Generic function variable Transformer toUpper = (s) => s.toUpperCase(); print(toUpper('hello')); // HELLO // Using type literals Type listType = List; print(listType); // List }

🚀 Advanced Features

🎯 Complete Definition

Modern Dart (3.x) includes powerful features: records, pattern matching, enhanced enums, class modifiers (sealed, base, final), extension methods, and more. These enable expressive, safe, and efficient code.

🚀 Cutting-edge

  • Records: Anonymous immutable aggregate ((String, int), (x: 1, y: 2)).
  • Pattern matching: Destructuring with switch and if case.
  • Sealed classes: Exhaustive subtype checking.
  • Extension methods: Add functionality to existing types.
  • Enhanced enums: Enums with fields, methods, and implements.
  • Class modifiers: sealed, base, final, interface for library control.
  • Async* / yield*: For streams.
// Records (Dart 3) void recordDemo() { var record = ('first', a: 2, b: true, 'last'); print(record.$1); // first print(record.a); // 2 print(record.$2); // last (positional after named) (String name, int age) person = ('Alice', 30); } // Pattern matching (Dart 3) void patternDemo(Object obj) { switch (obj) { case [int a, int b]: print('List with two ints: $a, $b'); case (int x, int y): print('Record with two ints: $x, $y'); case String s when s.length > 5: print('Long string: $s'); default: print('Something else'); } } // Extension methods extension StringCapitalize on String { String capitalize() { if (isEmpty) return this; return this[0].toUpperCase() + substring(1); } } // Sealed class example (conceptual) sealed class Shape {} class Circle implements Shape { final double radius; Circle(this.radius); } class Square implements Shape { final double side; Square(this.side); } double area(Shape shape) => switch (shape) { Circle(radius: var r) => 3.14 * r * r, Square(side: var s) => s * s, }; void main() { // Extension print('hello world'.capitalize()); // Hello world // Pattern matching patternDemo([1, 2]); // List with two ints: 1, 2 patternDemo((3, 4)); // Record with two ints: 3, 4 // Record usage recordDemo(); }