🚀 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).
📊 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 explicitString name = 'value'; - Constants:
final(set once),const(compile-time constant). - String interpolation:
'Hello $name'or'${expression}'. - Comments:
//,/* */,///(doc comments).
📦 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:
bool–trueorfalse. - Lists:
List<T>(array). - Sets:
Set<T>(unordered unique). - Maps:
Map<K,V>(key-value). - Runes: Unicode code points.
- Symbols: Opaque name identifiers.
🔢 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).
🔀 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++)andfor (var item in list). - while / do-while.
- switch: with patterns (Dart 3).
- assert:
assert(condition, 'message');only in debug.
⚙️ 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.
📋 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().
📝 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 + str2or adjacent string literals'Hello' 'World'. - Multiline:
''' ... '''or""" ... """. - Raw string:
r'C:\path\to\file'(no escapes). - Methods:
.length,.isEmpty,.toUpperCase(),.indexOf(),.startsWith().
🏗️ 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().
🔗 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.
⚡ 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 fororlisten(). - Isolate: For parallel computation (separate memory).
🛡️ 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
Exceptioninterface.
📦 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>[];
🚀 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
switchandif 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,interfacefor library control. - Async* / yield*: For streams.