---
title: "Dart"
lang: "en"
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/dart
---

[Home](/)›[Cheatsheets](/cheatsheets)

Cheatsheets

# Dart

Dart is a statically-typed, strongly null-safe programming language optimized for building fast, multi-platform applications, with async/await and object-oriented features.

7 Categories16 Sections40 ExamplesPublished: 01 Jan 2023Updated: 28 Feb 2025

DartProgrammingType SafetyNull SafetyOOPAsync/AwaitFlutterWeb Development

[Markdown for AI(opens in a new tab)](/dart/index.md "Open the plain-Markdown version of this page, for pasting into an AI tool")

Series

[Programming Languages](/series/programming-languages)1/4

[NextPython](/cheatsheets/python)

All posts in this series (4)

Cheatsheets4

1.  [DartYou are here](/cheatsheets/dart)
2.  [Python](/cheatsheets/python)
3.  [JavaScript](/cheatsheets/javascript)
4.  [Go](/cheatsheets/go)

Dart is a statically-typed, strongly null-safe programming language designed for building fast, multi-platform applications. Created by Google, Dart ships with its own compiler, formatter, and package manager for web, server, and mobile development.

Language features:

-   **Strong Null Safety**: The type system separates nullable from non-nullable types, so null reference errors are caught at compile time.
-   **Async/Await**: First-class support for asynchronous programming with futures, streams, and async/await syntax.
-   **Object-Oriented**: Full OOP support with classes, inheritance, mixins, and abstract classes.
-   **Generics**: A generic type system for reusable, type-safe code.
-   **Extensions**: Extend existing types with new methods without inheritance.
-   **Type Inference**: Automatic type inference while maintaining strict type safety.
-   **Hot Reload**: Rapid development cycle with instant code changes during debugging.

The categories below cover Dart syntax, advanced features, and best practices.

[Getting Started](#category-getting-started)

-   [Hello World](#section-hello-world)
-   [Variables](#section-variables)
-   [Null Safety](#section-null-safety)

[Data Types](#category-data-types)

-   [Numbers](#section-numbers)
-   [Strings](#section-strings)
-   [Collections](#section-collections)

[Control Flow](#category-control-flow)

-   [Conditional Statements](#section-conditional-statements)
-   [Loops](#section-loops)

[Functions & Methods](#category-functions)

-   [Function Basics](#section-function-basics)
-   [Advanced Functions](#section-advanced-functions)

[Object-Oriented Programming](#category-oop)

-   [Classes & Objects](#section-classes-objects)
-   [Inheritance & Polymorphism](#section-inheritance)

[Async Programming](#category-async-programming)

-   [Futures & Promises](#section-futures)
-   [Async/Await](#section-async-await)

[Advanced Features](#category-advanced-features)

-   [Generics](#section-generics)
-   [Extensions & Error Handling](#section-extensions-error-handling)

No commands found

Try adjusting your search term

## Getting Started

Fundamental Dart concepts and basic syntax for beginners.

### Hello World

Basic Dart program structure with main function and output.

#### Accessibility

Ensure code examples are properly syntax-highlighted for screen readers.

#### Best Practices

-   Use print() for debugging output in Dart programs.
-   Keep the main function as the entry point and delegate to other functions.
-   Use string interpolation instead of string concatenation for clarity.

#### Common Errors

-   **Missing main function:** Every Dart program must have a void main() function.
-   **Missing semicolons:** Dart requires semicolons at the end of statements.

#### Keywords

hello worldmainprintoutput

[Learn more](https://dart.dev/guides/language/language-tour)

#### Simple Hello World

A basic Dart program with main function that prints a greeting using print().

Code

```
1void main() {2  print('Hello, World!');3}
```

Execution

```
1dart main.dart
```

Output

```
1Hello, World!
```

-   Every Dart application must have a main() function.
-   main() is the entry point of the program.

#### Multiple print statements

Demonstrates calling print() multiple times to output different lines.

Code

```
1void main() {2  print('Welcome to Dart');3  print('Dart is awesome!');4  print('Multi-platform development');5}
```

Execution

```
1dart main.dart
```

Output

```
1Welcome to Dart2Dart is awesome!3Multi-platform development
```

-   print() adds a newline automatically.
-   Statements must end with semicolons in Dart.

#### String interpolation

Uses string interpolation with $ syntax to embed variables in strings.

Code

```
1void main() {2  String name = 'Dart';3  int version = 3;4  print('Welcome to $name version $version!');5}
```

Execution

```
1dart main.dart
```

Output

```
1Welcome to Dart version 3!
```

-   Use $ for simple variable insertion.
-   Use ${expression} for complex expressions in strings.

### Variables

Declaring and working with variables in Dart, including type inference and null safety.

#### Accessibility

Ensure variable declarations are clearly labeled with types.

#### Best Practices

-   Use var for local variables when type is obvious.
-   Use explicit types for function parameters and return types.
-   Use final for variables that won't change.
-   Use const for compile-time constants.

#### Common Errors

-   **Null reference exception:** Use null-aware operators (?, ??, ?.) for nullable types.
-   **Trying to reassign final variable:** final variables cannot be modified; use var instead if needed.

#### Advanced Notes

-   **Late variables:** Use late keyword for variables initialized later: late String value;
-   **Dynamic type:** Avoid dynamic when possible; use specific types or var for type safety.

#### Keywords

variablesvardynamiclatefinalconst

[Learn more](https://dart.dev/guides/language/language-tour#variables)

#### Variable declaration with type annotation

Demonstrates explicit variable declaration with type specification.

Code

```
1void main() {2  String name = 'Alice';3  int age = 30;4  double salary = 50000.50;5  bool isActive = true;6
7  print('$name is $age years old');8  print('Salary: $salary');9  print('Active: $isActive');10}
```

Execution

```
1dart main.dart
```

Output

```
1Alice is 30 years old2Salary: 50000.53Active: true
```

-   Type annotation comes before variable name.
-   Dart supports String, int, double, bool, and other types.

#### Type inference with var

Uses var keyword for type inference; Dart infers type from the assigned value.

Code

```
1void main() {2  var name = 'Bob';3  var count = 5;4  var price = 19.99;5
6  print('Name: $name');7  print('Count: $count');8  print('Price: $price');9}
```

Execution

```
1dart main.dart
```

Output

```
1Name: Bob2Count: 53Price: 19.99
```

-   var keyword makes code cleaner when type is obvious.
-   Dart still enforces strict typing after inference.

#### Final and const variables

Demonstrates final variables (runtime constant) and const (compile-time constant).

Code

```
1void main() {2  final String finalName = 'Charlie';3  const int maxRetries = 3;4
5  print('Final name: $finalName');6  print('Max retries: $maxRetries');7
8  // finalName = 'David'; // Error: can't assign9  // maxRetries = 5; // Error: can't assign10}
```

Execution

```
1dart main.dart
```

Output

```
1Final name: Charlie2Max retries: 3
```

-   final variables cannot be reassigned after initialization.
-   const is for compile-time constants; more restrictive than final.

### Null Safety

Dart's null safety feature and nullable vs non-nullable types.

#### Accessibility

Explain null safety concepts clearly for beginners.

#### Best Practices

-   Use non-nullable types by default; only use ? when necessary.
-   Always handle nullable types with null-aware operators.
-   Use null coalescing operator (??) for default values.

#### Common Errors

-   **Accessing property on nullable type:** Use ?. operator or check for null first.
-   **Type is not nullable but assigned null:** Change type to nullable with ? or remove null assignment.

#### Keywords

null safetynullablenon-nullablenull-aware operators

[Learn more](https://dart.dev/null-safety)

#### Non-nullable and nullable types

Demonstrates non-nullable (String) and nullable (String?) type declarations.

Code

```
1void main() {2  String name = 'Alice'; // Non-nullable3  String? nickName; // Nullable4
5  // name = null; // Error: can't assign null6  nickName = 'Ali';7  nickName = null; // OK8
9  print('Name: $name');10  print('Nickname: $nickName');11}
```

Execution

```
1dart main.dart
```

Output

```
1Name: Alice2Nickname: null
```

-   By default, types are non-nullable in Dart.
-   Add ? to make a type nullable.

#### Null-aware operators

Uses null-aware operators (?., ??, ??=) for safe null handling.

Code

```
1void main() {2  String? text;3
4  // Using ?. null-aware operator5  int? length = text?.length;6
7  // Using ?? null coalescing operator8  String value = text ?? 'Unknown';9
10  // Using ??= null assignment11  text ??= 'Hello';12
13  print('Length: $length');14  print('Value: $value');15  print('Text: $text');16}
```

Execution

```
1dart main.dart
```

Output

```
1Length: null2Value: Unknown3Text: Hello
```

-   ?. calls a method only if object is not null.
-   ?? provides default value if left side is null.
-   ??= assigns only if variable is null.

## Data Types

Dart's built-in data types including collections and commonly used types.

### Numbers

Working with int and double numeric types in Dart.

#### Accessibility

Ensure numeric operations are clearly explained.

#### Best Practices

-   Use int for whole numbers and double for decimal numbers.
-   Be aware of floating-point precision issues.
-   Use integer division ~/ when whole number result is needed.

#### Common Errors

-   **Precision issues with double arithmetic:** Use decimal package for precise calculations if needed.
-   **Type mismatch between int and double:** Cast explicitly: double val = 5.toDouble().

#### Keywords

numbersintdoublearithmeticoperations

[Learn more](https://dart.dev/guides/language/language-tour#numbers)

#### Integer operations

Demonstrates various arithmetic operations on integers.

Code

```
1void main() {2  int a = 10;3  int b = 3;4
5  print('Addition: ${a + b}');6  print('Subtraction: ${a - b}');7  print('Multiplication: ${a * b}');8  print('Division: ${a / b}');9  print('Integer Division: ${a ~/ b}');10  print('Remainder: ${a % b}');11}
```

Execution

```
1dart main.dart
```

Output

```
1Addition: 132Subtraction: 73Multiplication: 304Division: 3.33333333333333355Integer Division: 36Remainder: 1
```

-   ~/ performs integer division (floor division).
-   % returns the remainder of division.

#### Double and arithmetic

Shows operations on double type with decimal values.

Code

```
1void main() {2  double x = 10.5;3  double y = 3.2;4
5  print('Sum: ${x + y}');6  print('Product: ${x * y}');7  print('Power: ${x.pow(2)}');8  print('Absolute: ${(-5.5).abs()}');9}
```

Execution

```
1dart main.dart
```

Output

```
1Sum: 13.72Product: 33.63Power: 110.250000000000014Absolute: 5.5
```

-   pow() method calculates power; requires import 'dart:math'.
-   abs() returns absolute value.

### Strings

String manipulation, interpolation, and multi-line strings in Dart.

#### Accessibility

Show clear examples of string manipulation.

#### Best Practices

-   Use string interpolation instead of concatenation.
-   Use raw strings (r'...') for regex patterns without escaping.
-   Use triple quotes for text with multiple lines.

#### Common Errors

-   **Missing curly braces in interpolation:** Use ${expression} for expressions; $ works for simple variables.

#### Keywords

stringsconcatenationinterpolationmulti-line

[Learn more](https://dart.dev/guides/language/language-tour#strings)

#### String creation and interpolation

Demonstrates string interpolation with variables and expressions.

Code

```
1void main() {2  String firstName = 'John';3  String lastName = 'Doe';4  int age = 28;5
6  // String interpolation7  print('Full name: $firstName $lastName');8  print('Age: $age');9  print('Message: ${firstName.toUpperCase()} is $age years old');10}
```

Execution

```
1dart main.dart
```

Output

```
1Full name: John Doe2Age: 283Message: JOHN is 28 years old
```

-   Use $ for simple variables and ${expr} for complex expressions.
-   String methods like toUpperCase() work on interpolations.

#### Multi-line strings

Uses triple quotes for multi-line strings preserving formatting.

Code

```
1void main() {2  String poem = '''3  Roses are red,4  Violets are blue,5  Dart is awesome,6  And so are you!7  ''';8
9  print(poem);10  print('Length: ${poem.length}');11}
```

Execution

```
1dart main.dart
```

Output

```
1Roses are red,2Violets are blue,3Dart is awesome,4And so are you!5Length: 68
```

-   Triple quotes (''' or """) are used for multi-line strings.
-   Preserves newlines and indentation.

#### String methods

Demonstrates common string manipulation methods.

Code

```
1void main() {2  String text = 'Dart Programming';3
4  print('Original: $text');5  print('Uppercase: ${text.toUpperCase()}');6  print('Lowercase: ${text.toLowerCase()}');7  print('Contains "Prog": ${text.contains("Prog")}');8  print('Index of "P": ${text.indexOf("P")}');9  print('Substring: ${text.substring(0, 4)}');10}
```

Execution

```
1dart main.dart
```

Output

```
1Original: Dart Programming2Uppercase: DART PROGRAMMING3Lowercase: dart programming4Contains "Prog": true5Index of "P": 56Substring: Dart
```

-   contains() checks if substring exists.
-   indexOf() returns position of first match or -1.
-   substring() extracts part of string.

### Collections

Working with lists, maps, and sets in Dart.

#### Accessibility

Ensure collection operations are clearly explained.

#### Best Practices

-   Use containsKey() on maps to check whether a key exists.
-   Remember collections are mutable by default.
-   Use final for collections that won't be reassigned.

#### Common Errors

-   **Accessing non-existent map key returns null:** Use containsKey() or ?. operator to check first.
-   **Cannot modify unmodifiable collection:** Use List<int> instead of const if modification needed.

#### Keywords

collectionslistmapsetarray

[Learn more](https://dart.dev/guides/language/language-tour#collections)

#### Lists

Creates and manipulates lists with type parameters.

Code

```
1void main() {2  List<int> numbers = [1, 2, 3, 4, 5];3  List<String> colors = ['red', 'green', 'blue'];4
5  print('Numbers: $numbers');6  print('First: ${numbers.first}');7  print('Last: ${numbers.last}');8  print('Length: ${numbers.length}');9
10  numbers.add(6);11  print('After add: $numbers');12}
```

Execution

```
1dart main.dart
```

Output

```
1Numbers: [1, 2, 3, 4, 5]2First: 13Last: 54Length: 55After add: [1, 2, 3, 4, 5, 6]
```

-   Lists are ordered, mutable collections.
-   Use List<Type> for typed lists.
-   add() appends element to end of list.

#### Maps

Creates and manipulates maps with key-value pairs.

Code

```
1void main() {2  Map<String, int> scores = {3    'Alice': 90,4    'Bob': 85,5    'Charlie': 926  };7
8  print('Scores: $scores');9  print('Alice: ${scores['Alice']}');10  print('Keys: ${scores.keys}');11  print('Values: ${scores.values}');12
13  scores['David'] = 88;14  print('After add: $scores');15}
```

Execution

```
1dart main.dart
```

Output

```
1Scores: {Alice: 90, Bob: 85, Charlie: 92}2Alice: 903Keys: (Alice, Bob, Charlie)4Values: (90, 85, 92)5After add: {Alice: 90, Bob: 85, Charlie: 92, David: 88}
```

-   Maps store key-value pairs where keys are unique.
-   Use Map<KeyType, ValueType> for typed maps.

#### Sets and iteration

Creates and manipulates sets (unordered, unique collections).

Code

```
1void main() {2  Set<String> languages = {'Dart', 'Java', 'Python'};3
4  print('Languages: $languages');5  print('Length: ${languages.length}');6  print('Contains Dart: ${languages.contains("Dart")}');7
8  languages.add('JavaScript');9  languages.add('Dart'); // Duplicate, ignored10
11  for (var lang in languages) {12    print('- $lang');13  }14}
```

Execution

```
1dart main.dart
```

Output

```
1Languages: {Dart, Java, Python}2Length: 33Contains Dart: true4- Dart5- Java6- Python7- JavaScript
```

-   Sets contain only unique elements.
-   Duplicates are automatically ignored.

## Control Flow

Decision making and loop structures in Dart.

### Conditional Statements

If, else, and switch statements for decision making.

#### Accessibility

Ensure conditional logic is clearly explained.

#### Best Practices

-   Use if-else for complex boolean logic.
-   Use switch for single value against multiple options.
-   Use ternary only for simple conditions.

#### Common Errors

-   **Fall-through in switch without break:** Add break; at end of case block.
-   **Missing default case:** Add default case to handle unexpected values.

#### Keywords

ifelseswitchternaryconditional

[Learn more](https://dart.dev/guides/language/language-tour#control-flow-statements)

#### If and else statements

Demonstrates if-else if-else chain for multiple conditions.

Code

```
1void main() {2  int age = 20;3
4  if (age < 13) {5    print('Child');6  } else if (age < 18) {7    print('Teenager');8  } else if (age < 65) {9    print('Adult');10  } else {11    print('Senior');12  }13}
```

Execution

```
1dart main.dart
```

Output

```
1Adult
```

-   Use more specific conditions first in if-else chains.
-   The last matching condition executes.

#### Ternary operator

Uses ternary operator for short conditional assignments.

Code

```
1void main() {2  int score = 75;3  String result = score >= 60 ? 'Pass' : 'Fail';4
5  print('Score: $score');6  print('Result: $result');7
8  String grade = score >= 90 ? 'A' :9                 score >= 80 ? 'B' :10                 score >= 70 ? 'C' : 'F';11  print('Grade: $grade');12}
```

Execution

```
1dart main.dart
```

Output

```
1Score: 752Result: Pass3Grade: C
```

-   Ternary operator: condition ? trueValue : falseValue
-   Can chain ternary operators for multiple conditions.

#### Switch statement

Uses switch statement for multi-way branching on a single value.

Code

```
1void main() {2  String day = 'Monday';3
4  switch (day) {5    case 'Monday':6      print('Start of work week');7      break;8    case 'Friday':9      print('Almost weekend!');10      break;11    case 'Saturday':12    case 'Sunday':13      print('Weekend');14      break;15    default:16      print('Midweek');17  }18}
```

Execution

```
1dart main.dart
```

Output

```
1Start of work week
```

-   Use break to prevent fall-through to next case.
-   Multiple cases can execute same code (case fallthrough).

### Loops

For, while, and do-while loops for iteration.

#### Accessibility

Explain loop syntax and iteration clearly.

#### Best Practices

-   Use for loops with ranges when you know the iteration count.
-   Use for-in for iterating over collections.
-   Use while for condition-based loops.

#### Common Errors

-   **Infinite loop:** Make sure the loop condition eventually becomes false.
-   **Off-by-one errors:** Carefully check loop bounds and conditions.

#### Keywords

loopsforwhiledo-whileiteration

[Learn more](https://dart.dev/guides/language/language-tour#control-flow-statements)

#### For loops

Demonstrates traditional for loop and for-in loop over collections.

Code

```
1void main() {2  // Traditional for loop3  for (int i = 0; i < 5; i++) {4    print('Count: $i');5  }6
7  print('---');8
9  // For-in loop10  List<String> fruits = ['Apple', 'Banana', 'Cherry'];11  for (var fruit in fruits) {12    print('Fruit: $fruit');13  }14}
```

Execution

```
1dart main.dart
```

Output

```
1Count: 02Count: 13Count: 24Count: 35Count: 46---7Fruit: Apple8Fruit: Banana9Fruit: Cherry
```

-   Traditional for: for (init; condition; increment)
-   For-in loop iterates over collections directly.

#### While and do-while loops

Shows while loop (checks condition before) and do-while (checks after).

Code

```
1void main() {2  // While loop3  int count = 0;4  while (count < 3) {5    print('While: $count');6    count++;7  }8
9  print('---');10
11  // Do-while loop12  int num = 0;13  do {14    print('Do-while: $num');15    num++;16  } while (num < 3);17}
```

Execution

```
1dart main.dart
```

Output

```
1While: 02While: 13While: 24---5Do-while: 06Do-while: 17Do-while: 2
```

-   While loop tests condition before executing body.
-   Do-while loop executes body at least once.

#### Break and continue

Uses break to exit loop early and continue to skip iteration.

Code

```
1void main() {2  // Break example3  for (int i = 0; i < 10; i++) {4    if (i == 5) break;5    print('Break loop: $i');6  }7
8  print('---');9
10  // Continue example11  for (int i = 0; i < 5; i++) {12    if (i == 2) continue;13    print('Continue loop: $i');14  }15}
```

Execution

```
1dart main.dart
```

Output

```
1Break loop: 02Break loop: 13Break loop: 24Break loop: 35Break loop: 46---7Continue loop: 08Continue loop: 19Continue loop: 310Continue loop: 4
```

-   break exits the loop immediately.
-   continue skips remaining code in current iteration.

## Functions & Methods

Declaring and using functions in Dart with parameters and return types.

### Function Basics

Function declaration, parameters, and return types.

#### Accessibility

Ensure function signatures are clearly explained.

#### Best Practices

-   Use descriptive function names that indicate what they do.
-   Keep functions focused on a single responsibility.
-   Use type annotations for clarity and type safety.

#### Common Errors

-   **Missing return type:** Always specify return type or use void.
-   **Parameter type mismatch on call:** Match the argument types to the parameter declarations.

#### Keywords

functionsmethodsparametersreturnvoid

[Learn more](https://dart.dev/guides/language/language-tour#functions)

#### Basic function declaration

Demonstrates function declaration with parameters and return types.

Code

```
1void greet(String name) {2  print('Hello, $name!');3}4
5int add(int a, int b) {6  return a + b;7}8
9void main() {10  greet('Alice');11  int result = add(5, 3);12  print('Sum: $result');13}
```

Execution

```
1dart main.dart
```

Output

```
1Hello, Alice!2Sum: 8
```

-   ReturnType functionName(parameters) { body }
-   Use void for functions that don't return a value.

#### Optional and named parameters

Uses named parameters in curly braces for flexible function calls.

Code

```
1void printInfo(String name, {int? age, String? city}) {2  print('Name: $name');3  if (age != null) print('Age: $age');4  if (city != null) print('City: $city');5}6
7void main() {8  printInfo('Alice');9  printInfo('Bob', age: 30);10  printInfo('Charlie', age: 25, city: 'NYC');11}
```

Execution

```
1dart main.dart
```

Output

```
1Name: Alice2Name: Bob3Age: 304Name: Charlie5Age: 256City: NYC
```

-   Named parameters are optional by default.
-   Required named parameters use 'required' keyword.

#### Arrow functions and default values

Uses arrow syntax (=>) for concise function body and default parameter values.

Code

```
1int square(int x) => x * x;2
3void printMessage(String msg, {String prefix = 'INFO'}) {4  print('[$prefix] $msg');5}6
7void main() {8  print('Square of 5: ${square(5)}');9
10  printMessage('Application started');11  printMessage('Error occurred', prefix: 'ERROR');12}
```

Execution

```
1dart main.dart
```

Output

```
1Square of 5: 252[INFO] Application started3[ERROR] Error occurred
```

-   \=> syntax works only for single expressions.
-   Default values provided with = in parameter list.

### Advanced Functions

Anonymous functions, closures, and higher-order functions.

#### Accessibility

Explain function types and closures clearly.

#### Best Practices

-   Use map(), filter(), reduce() for functional style code.
-   Prefer closures over class methods when appropriate.
-   Consider performance for nested anonymous functions.

#### Common Errors

-   **Modified variable after closure created:** Closures capture by reference; be careful with mutable state.

#### Keywords

anonymous functionsclosureshigher-order functionscallbackslambda

[Learn more](https://dart.dev/guides/language/language-tour#functions)

#### Anonymous functions and callbacks

Demonstrates anonymous functions used with collection methods.

Code

```
1void main() {2  List<int> numbers = [1, 2, 3, 4, 5];3
4  // Anonymous function with forEach5  numbers.forEach((num) {6    print('Number: $num');7  });8
9  print('---');10
11  // Arrow syntax anonymous function12  List<int> squared = numbers.map((x) => x * x).toList();13  print('Squared: $squared');14}
```

Execution

```
1dart main.dart
```

Output

```
1Number: 12Number: 23Number: 34Number: 45Number: 56---7Squared: [1, 4, 9, 16, 25]
```

-   Anonymous functions are lambdas without explicit declaration.
-   Use => for concise anonymous function bodies.

#### Closures

Demonstrates closures that capture variables from outer scope.

Code

```
1Function makeMultiplier(int factor) {2  return (int value) {3    return value * factor;4  };5}6
7void main() {8  var double = makeMultiplier(2);9  var triple = makeMultiplier(3);10
11  print('2 * 5 = ${double(5)}');12  print('3 * 5 = ${triple(5)}');13}
```

Execution

```
1dart main.dart
```

Output

```
12 * 5 = 1023 * 5 = 15
```

-   Closures capture variables from enclosing scope.
-   Each closure maintains its own captured state.

## Object-Oriented Programming

Classes, objects, inheritance, and advanced OOP concepts in Dart.

### Classes & Objects

Defining classes, creating objects, and using constructors.

#### Accessibility

Explain class structure and instantiation clearly.

#### Best Practices

-   Use meaningful class and property names.
-   Keep methods focused on single responsibility.
-   Use getters/setters instead of public fields when behavior needed.

#### Common Errors

-   **Accessing undefined property:** Declare the property in the class.
-   **Constructor parameter not assigned to field:** Use this.fieldName or explicit assignment.

#### Keywords

classesobjectsconstructorspropertiesmethods

[Learn more](https://dart.dev/guides/language/language-tour#classes)

#### Basic class definition

Demonstrates class definition with properties, constructor, and methods.

Code

```
1class Person {2  String name;3  int age;4
5  Person(this.name, this.age);6
7  void displayInfo() {8    print('Name: $name, Age: $age');9  }10}11
12void main() {13  var person = Person('Alice', 30);14  person.displayInfo();15  print('${person.name} is ${person.age} years old');16}
```

Execution

```
1dart main.dart
```

Output

```
1Name: Alice, Age: 302Alice is 30 years old
```

-   Constructor syntax: ClassName(parameters)
-   Use this.property for automatic field assignment.

#### Multiple constructors

Shows named constructors for different object initialization patterns.

Code

```
1class Point {2  double x, y;3
4  Point(this.x, this.y);5
6  Point.origin() : x = 0, y = 0;7
8  Point.fromList(List<double> coords) : x = coords[0], y = coords[1];9
10  void display() => print('($x, $y)');11}12
13void main() {14  var p1 = Point(3, 4);15  var p2 = Point.origin();16  var p3 = Point.fromList([5, 6]);17
18  p1.display();19  p2.display();20  p3.display();21}
```

Execution

```
1dart main.dart
```

Output

```
1(3.0, 4.0)2(0.0, 0.0)3(5.0, 6.0)
```

-   Named constructors use ClassName.constructorName syntax.
-   Use: for initializer list before constructor body.

#### Getters and setters

Uses getters and setters for computed properties and controlled access.

Code

```
1class Rectangle {2  double width, height;3
4  Rectangle(this.width, this.height);5
6  double get area => width * height;7
8  set width(double w) {9    if (w > 0) width = w;10  }11
12  String get dimensions => '$width x $height';13}14
15void main() {16  var rect = Rectangle(5, 3);17  print('Area: ${rect.area}');18  print('Dimensions: ${rect.dimensions}');19}
```

Execution

```
1dart main.dart
```

Output

```
1Area: 15.02Dimensions: 5.0 x 3.0
```

-   Getters compute values on-the-fly.
-   Setters allow controlled property assignment.

### Inheritance & Polymorphism

Extending classes, method overriding, and polymorphic behavior.

#### Accessibility

Explain inheritance relationships clearly.

#### Best Practices

-   Use meaningful inheritance hierarchies.
-   Prefer composition over inheritance when possible.
-   Use abstract classes to define contracts.

#### Common Errors

-   **Cannot instantiate abstract class:** Either implement abstract methods or use concrete subclass.
-   **Method signature mismatch in override:** Give the overriding method a compatible signature.

#### Keywords

inheritanceextendsoverridesuperpolymorphism

[Learn more](https://dart.dev/guides/language/language-tour#classes)

#### Class inheritance and super

Demonstrates inheritance with extends and method overriding.

Code

```
1class Animal {2  String name;3
4  Animal(this.name);5
6  void makeSound() {7    print('$name makes a sound');8  }9}10
11class Dog extends Animal {12  Dog(String name) : super(name);13
14  @override15  void makeSound() {16    print('$name barks');17  }18}19
20void main() {21  var dog = Dog('Rex');22  dog.makeSound();23}
```

Execution

```
1dart main.dart
```

Output

```
1Rex barks
```

-   Use extends to inherit from a class.
-   Use super() to call parent constructor.
-   Use @override annotation when overriding methods.

#### Abstract classes and interfaces

Uses abstract classes and implements contracts for polymorphism.

Code

```
1abstract class Shape {2  double get area;3  void display();4}5
6class Circle implements Shape {7  double radius;8
9  Circle(this.radius);10
11  @override12  double get area => 3.14159 * radius * radius;13
14  @override15  void display() => print('Circle with radius $radius, area: ${area.toStringAsFixed(2)}');16}17
18void main() {19  var circle = Circle(5);20  circle.display();21}
```

Execution

```
1dart main.dart
```

Output

```
1Circle with radius 5, area: 78.54
```

-   Abstract classes define contract with unimplemented methods.
-   implements keyword creates interface implementation contract.

## Async Programming

Futures, async/await, and streams for asynchronous operations.

### Futures & Promises

Working with Future objects for asynchronous operations.

#### Accessibility

Explain async concepts and Future handling.

#### Best Practices

-   Use async/await instead of chains of then().
-   Always handle errors in futures.
-   Use Future.wait for parallel operations.

#### Common Errors

-   **Uncaught exceptions in futures:** Always add catchError() or await in try-catch.
-   **Blocking on async operations:** Use await in async functions, not synchronous code.

#### Keywords

futuresasyncpromisesthencallbacks

[Learn more](https://dart.dev/guides/language/language-tour#asynchrony-support)

#### Creating and handling futures

Demonstrates Future creation and handling with then/catchError.

Code

```
1Future<String> fetchData() {2  return Future.delayed(Duration(seconds: 1), () {3    return 'Data loaded';4  });5}6
7void main() {8  print('Fetching data...');9
10  fetchData().then((data) {11    print('Result: $data');12  }).catchError((error) {13    print('Error: $error');14  });15
16  print('Request sent');17}
```

Execution

```
1dart main.dart
```

Output

```
1Fetching data...2Request sent3Result: Data loaded
```

-   Future represents a value that will be available later.
-   then() executes when Future completes successfully.
-   catchError() handles exceptions in Future.

#### Future.wait and multiple futures

Uses Future.wait to handle multiple concurrent futures.

Code

```
1Future<int> calculateSum(int a, int b) {2  return Future.delayed(Duration(milliseconds: 500), () => a + b);3}4
5void main() async {6  print('Starting calculations...');7
8  var result = await Future.wait([9    calculateSum(5, 3),10    calculateSum(10, 2),11    calculateSum(7, 4)12  ]);13
14  print('Results: $result');15}
```

Execution

```
1dart main.dart
```

Output

```
1Results: [8, 12, 11]
```

-   Future.wait waits for all futures to complete.
-   Returns list of results in same order as inputs.

### Async/Await

Using async/await syntax for cleaner asynchronous code.

#### Accessibility

Explain async/await syntax and error handling.

#### Best Practices

-   Use async/await instead of Future.then() chains.
-   Always wrap await calls in try-catch when errors expected.
-   Use finally for cleanup operations.

#### Common Errors

-   **Await outside async function:** Add async keyword to function signature.
-   **Unhandled exceptions in async functions:** Add try-catch around await expressions.

#### Keywords

asyncawaitasynchronoustry-catch

[Learn more](https://dart.dev/guides/language/language-tour#asynchrony-support)

#### Basic async/await

Demonstrates async function with await for sequential async operations.

Code

```
1Future<int> fetchNumber() {2  return Future.delayed(Duration(seconds: 1), () => 42);3}4
5void main() async {6  print('Fetching number...');7
8  int number = await fetchNumber();9  print('Number: $number');10
11  int doubled = number * 2;12  print('Doubled: $doubled');13}
```

Execution

```
1dart main.dart
```

Output

```
1Fetching number...2Number: 423Doubled: 84
```

-   await pauses execution until Future completes.
-   await can only be used in async functions.

#### Error handling with try-catch

Uses try-catch-finally to catch and handle async errors.

Code

```
1Future<String> riskyOperation(bool shouldFail) {2  return Future.delayed(Duration(milliseconds: 500), () {3    if (shouldFail) {4      throw Exception('Operation failed');5    }6    return 'Success';7  });8}9
10void main() async {11  try {12    var result = await riskyOperation(false);13    print('Result: $result');14
15    await riskyOperation(true);16  } catch (e) {17    print('Error caught: $e');18  } finally {19    print('Operation completed');20  }21}
```

Execution

```
1dart main.dart
```

Output

```
1Result: Success2Error caught: Exception: Operation failed3Operation completed
```

-   try-catch works with await for async exceptions.
-   finally block always executes regardless of success or error.

## Advanced Features

Generics, extensions, pattern matching, and advanced language features.

### Generics

Creating reusable generic classes and methods.

#### Accessibility

Explain generic type syntax clearly.

#### Best Practices

-   Use generics to create reusable, type-safe code.
-   Bound generics when methods require specific capabilities.
-   Avoid using dynamic when generics can provide type safety.

#### Common Errors

-   **Type mismatch with generic:** Match the actual type to the declared type parameter.

#### Keywords

genericstype parameterstemplatesbounded types

[Learn more](https://dart.dev/guides/language/language-tour#generics)

#### Generic classes and methods

Implements generic Stack class that works with any type.

Code

```
1class Stack<T> {2  final List<T> items = [];3
4  void push(T value) => items.add(value);5  T pop() => items.removeLast();6  bool get isEmpty => items.isEmpty;7}8
9void main() {10  var intStack = Stack<int>();11  intStack.push(1);12  intStack.push(2);13  print('Popped: ${intStack.pop()}');14
15  var stringStack = Stack<String>();16  stringStack.push('Hello');17  stringStack.push('World');18  print('Popped: ${stringStack.pop()}');19}
```

Execution

```
1dart main.dart
```

Output

```
1Popped: 22Popped: World
```

-   Use <T> as type parameter placeholder.
-   Specify concrete type when instantiating: Stack<int>().

#### Bounded generic types

Demonstrates bounded generics restricting type parameter to subtype.

Code

```
1class Comparable<T extends num> {2  T value;3
4  Comparable(this.value);5
6  bool isGreaterThan(T other) => value > other;7
8  T getDouble() => (value * 2) as T;9}10
11void main() {12  var intComp = Comparable<int>(10);13  print('10 > 5? ${intComp.isGreaterThan(5)}');14
15  var doubleComp = Comparable<double>(3.5);16  print('3.5 > 2.0? ${doubleComp.isGreaterThan(2.0)}');17}
```

Execution

```
1dart main.dart
```

Output

```
110 > 5? true23.5 > 2.0? true
```

-   Use extends to bound type parameter to specific type.
-   Allows using methods specific to bound type.

### Extensions & Error Handling

Extension methods, custom exceptions, and error handling patterns.

#### Accessibility

Explain extensions and exception handling clearly.

#### Best Practices

-   Create extension methods for common operations.
-   Create specific exception types for different error conditions.
-   Use on clause to handle specific exceptions differently.

#### Common Errors

-   **Uncaught exception type:** Add on clause for specific exception before generic catch.
-   **Extension method not found:** Import the extension, or define it in the current scope.

#### Keywords

extensionscustom exceptionserror handlingtry-catch

[Learn more](https://dart.dev/guides/language/language-tour#libraries-and-visibility)

#### Extension methods

Demonstrates extension methods adding functionality to existing types.

Code

```
1extension StringExtensions on String {2  bool get isEmail => contains('@');3
4  String capitalize() {5    if (isEmpty) return this;6    return this[0].toUpperCase() + substring(1);7  }8}9
10void main() {11  String text = 'hello world';12  print('Capitalized: ${text.capitalize()}');13
14  String email = 'user@example.com';15  print('Is email: ${email.isEmail}');16}
```

Execution

```
1dart main.dart
```

Output

```
1Capitalized: Hello world2Is email: true
```

-   Extensions add methods to classes without inheritance.
-   Can add getters, setters, and methods.

#### Custom exceptions and error handling

Defines custom exception and handles specific exception types.

Code

```
1class InvalidAgeException implements Exception {2  String message;3  InvalidAgeException(this.message);4
5  @override6  String toString() => message;7}8
9void validateAge(int age) {10  if (age < 0 || age > 150) {11    throw InvalidAgeException('Age must be between 0 and 150');12  }13}14
15void main() {16  try {17    validateAge(25);18    print('Age is valid');19
20    validateAge(-5);21  } on InvalidAgeException catch (e) {22    print('Error: $e');23  } catch (e) {24    print('Unexpected error: $e');25  }26}
```

Execution

```
1dart main.dart
```

Output

```
1Age is valid2Error: Age must be between 0 and 150
```

-   Implement Exception interface for custom exceptions.
-   Use the on clause to catch a specific exception type.

Was this useful?

## Tags

#Dart#Programming#Type Safety#Null Safety#OOP#Async/Await#Flutter#Web Development

## Share

[Facebook](https://facebook.com/sharer/sharer.php?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fdart "Share on Facebook")[Twitter](https://twitter.com/intent/tweet/?text=Dart&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fdart "Share on Twitter")[LinkedIn](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fdart&title=Dart&summary=Dart%20is%20a%20statically-typed%2C%20strongly%20null-safe%20programming%20language%20optimized%20for%20building%20fast%2C%20multi-platform%20applications%2C%20with%20async%2Fawait%20and%20object-oriented%20features.&source=https://mkabumattar.com "Share on LinkedIn")[WhatsApp](https://wa.me/?text=Dart%20https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fdart "Share on WhatsApp")[Telegram](https://t.me/share/url?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fdart&text=Dart "Share on Telegram")[Reddit](https://www.reddit.com/submit?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fdart&title=Dart "Share on Reddit")[Hacker News](http://news.ycombinator.com/submitlink?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fdart&t=Dart "Share on Hacker News")[Pinterest](https://pinterest.com/pin/create/button/?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fdart&media=&description=Dart%20is%20a%20statically-typed%2C%20strongly%20null-safe%20programming%20language%20optimized%20for%20building%20fast%2C%20multi-platform%20applications%2C%20with%20async%2Fawait%20and%20object-oriented%20features. "Share on Pinterest")[Email](<mailto:?subject=Dart&body=Check out this article: https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fdart>)

## Comments

## You might also enjoy

More posts on similar topics

## [JavaScript](/cheatsheets/javascript)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Programming Language
-   Web Development
-   Frontend
-   Backend
-   Scripting

JavaScript is a high-level programming language that powers the web. It supports object-oriented, functional, and event-driven programming styles. The sections below cover JavaScript syntax and metho

#JavaScript#ES6#Web Development+3 tags

[read more](/cheatsheets/javascript)

## [Python](/cheatsheets/python)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Programming Language
-   Python
-   Scripting
-   Object Oriented
-   Web Development
-   Data Science

Python is an interpreted, high-level programming language known for its readability and simplicity. It supports multiple programming paradigms including procedural, object-oriented, and functional pro

#Python#Programming#Scripting+6 tags

[read more](/cheatsheets/python)

## [Go](/cheatsheets/go)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Programming Language
-   Go
-   Systems Programming
-   Web Development
-   Backend
-   Concurrency

Go is a statically typed, compiled programming language designed with simplicity and efficiency in mind. It excels at concurrent programming, which makes it a good fit for fast, scalable server applic

#Go#Golang#Programming+6 tags

[read more](/cheatsheets/go)

## [Curl](/cheatsheets/curl)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Web Development
-   APIs
-   HTTP
-   Command Line
-   Tools

Getting started with Curl cURL (client URL) is a command-line tool for transferring data using URLs. It speaks HTTP, HTTPS, FTP, SFTP, and many other protocols, which makes it the usual choice for

#Curl#HTTP#REST+3 tags

[read more](/cheatsheets/curl)

## [AWK](/cheatsheets/awk)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Text Processing
-   Linux
-   Command Line
-   Development Tools
-   Scripting

AWK complete reference guide Quick start Print entire file awk '{ print }' file.txt# Print specific column awk '{ print $1 }' file.txt# Print lines matching pattern awk '/patter

#AWK#Text Processing#Pattern Matching+3 tags

[read more](/cheatsheets/awk)

## [Bash](/cheatsheets/bash)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Scripting
-   Shell
-   Linux
-   Unix
-   Command Line
-   Automation

Bash is a Unix shell and command language written by Brian Fox for the GNU Project as a free software replacement for the Bourne shell. The sections below cover Bash commands, syntax, and examples.

#Scripting#Shell#Linux+3 tags

[read more](/cheatsheets/bash)

6 related posts
