Dart
Updated: September 8, 2025Categories: Languages, Mobile
Printed from:
Dart Cheatsheet
Language Overview
Dart is a client-optimized programming language developed by Google, designed for building mobile, web, desktop, and server applications. Key features include:
- Strong typing with sound null safety
- Object-oriented and class-based
- Supports both ahead-of-time (AOT) and just-in-time (JIT) compilation
- Primary language for Flutter cross-platform development
- Supports functional and reactive programming paradigms
Basic Syntax
Hello World
dart
1234void main() { print('Hello, Dart!'); }
Comments
dart
1234567// Single-line comment /* Multi-line comment */ /// Documentation comment
Data Types
Primitive Types
dart
12345678910111213141516171819// Integer int age = 30; // Double double height = 1.75; // String String name = 'John Doe'; // Boolean bool isActive = true; // Dynamic (avoid when possible) dynamic variable = 42; // Null safety String? nullableString; // Can be null String nonNullableString = 'Hello'; // Cannot be null
Null Safety
dart
12345678// Late initialization late String description; // Will be initialized before use // Null-aware operators String? name = null; print(name?.length); // Safely access nullable property print(name ?? 'Unknown'); // Provide default value
Collection Types
dart
12345678910111213141516171819// List List<int> numbers = [1, 2, 3, 4, 5]; List<String> fruits = ['apple', 'banana', 'cherry']; // Set Set<String> uniqueColors = {'red', 'green', 'blue'}; // Map Map<String, int> ages = { 'Alice': 30, 'Bob': 25, 'Charlie': 35 }; // Spread operator List<int> list1 = [1, 2, 3]; List<int> list2 = [4, 5, 6]; List<int> combinedList = [...list1, ...list2];
Variables and Constants
dart
12345678910111213// Variables var dynamicVar = 42; // Type inferred int explicitInt = 10; // Final (runtime constant) final String name = 'John'; // Const (compile-time constant) const double pi = 3.14159; // Late variables late String expensiveComputation;
Operators
Arithmetic Operators
dart
12345678int a = 10, b = 5; print(a + b); // Addition print(a - b); // Subtraction print(a * b); // Multiplication print(a / b); // Division print(a % b); // Modulo print(a ~/ b); // Integer division
Comparison Operators
dart
1234567print(a == b); // Equal print(a != b); // Not equal print(a > b); // Greater than print(a < b); // Less than print(a >= b); // Greater than or equal print(a <= b); // Less than or equal
Logical Operators
dart
12345bool x = true, y = false; print(!x); // Logical NOT print(x && y); // Logical AND print(x || y); // Logical OR
Control Structures
Conditional Statements
dart
123456789101112// If-else if (condition) { // Code } else if (anotherCondition) { // Alternative code } else { // Default code } // Ternary operator var result = condition ? trueValue : falseValue;
Loops
dart
12345678910111213141516171819202122232425262728293031// For loop for (int i = 0; i < 5; i++) { print(i); } // For-in loop List<String> fruits = ['apple', 'banana', 'cherry']; for (var fruit in fruits) { print(fruit); } // While loop int counter = 0; while (counter < 5) { print(counter); counter++; } // Do-while loop do { print(counter); counter++; } while (counter < 10); // Break and continue for (int i = 0; i < 10; i++) { if (i == 5) break; // Exit loop if (i % 2 == 0) continue; // Skip even numbers print(i); }
Functions
Basic Functions
dart
123456789101112131415161718// Function declaration int add(int a, int b) { return a + b; } // Optional parameters void greet(String name, {int? age}) { print('Hello $name, ${age != null ? "you are $age" : ""}'); } // Named parameters void printUser({required String name, int age = 0}) { print('Name: $name, Age: $age'); } // Arrow function syntax int multiply(int a, int b) => a * b;
Anonymous Functions (Closures)
dart
12345var numbers = [1, 2, 3, 4]; numbers.forEach((number) { print(number * 2); });
Async Programming
dart
12345678910111213141516// Async function Future<String> fetchData() async { await Future.delayed(Duration(seconds: 2)); return 'Data fetched'; } // Async with error handling Future<void> asyncExample() async { try { String result = await fetchData(); print(result); } catch (e) { print('Error: $e'); } }
Object-Oriented Programming
Classes and Objects
dart
1234567891011121314151617181920212223class Person { // Instance variables String name; int age; // Constructor Person(this.name, this.age); // Named constructor Person.fromJson(Map<String, dynamic> json) : name = json['name'], age = json['age']; // Method void introduce() { print('Hi, I\'m $name and I\'m $age years old'); } } // Usage var person = Person('Alice', 30); person.introduce();
Inheritance
dart
12345678910111213class Employee extends Person { String position; Employee(String name, int age, this.position) : super(name, age); @override void introduce() { super.introduce(); print('My position is $position'); } }
Mixins
dart
12345678mixin Swimmer { void swim() { print('Swimming'); } } class Fish extends Animal with Swimmer {}
Error Handling
dart
1234567891011121314151617try { // Risky code int result = 10 ~/ 0; // Throws IntegerDivisionByZeroException } on IntegerDivisionByZeroException { print('Cannot divide by zero'); } catch (e) { print('Unexpected error: $e'); } finally { print('Always executed'); } // Custom exceptions class CustomException implements Exception { String message; CustomException(this.message); }
File I/O
dart
123456789101112131415import 'dart:io'; // Reading a file Future<void> readFile() async { File file = File('example.txt'); String contents = await file.readAsString(); print(contents); } // Writing to a file Future<void> writeFile() async { File file = File('output.txt'); await file.writeAsString('Hello, File!'); }
Concurrency with Isolates
dart
12345678910111213141516import 'dart:isolate'; void heavyComputation(SendPort sendPort) { // Perform complex computation int result = 42; sendPort.send(result); } Future<void> runIsolate() async { final receivePort = ReceivePort(); await Isolate.spawn(heavyComputation, receivePort.sendPort); final result = await receivePort.first; print('Result from isolate: $result'); }
Pub Package Management
Bash
123456789# Install a package
dart pub add http
# Upgrade packages
dart pub upgrade
# Run a package
dart pub run package_name
Common Libraries and Frameworks
Standard Libraries
dart:core: Core functionalitydart:async: Asynchronous programmingdart:io: File and system operationsdart:math: Mathematical functions
Popular Third-Party Packages
http: HTTP requestsprovider: State managementdio: Advanced HTTP networkingbloc: State managementjson_serializable: JSON serialization
Flutter Specific
dart
123456789101112131415// Basic Flutter Widget import 'package:flutter/material.dart'; class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text('My App')), body: Center(child: Text('Hello, Flutter!')), ), ); } }
Best Practices
Code Style
- Use meaningful variable and function names
- Follow dart_style guidelines
- Use
dartfmtfor consistent formatting
Performance Tips
- Use
constconstructors when possible - Minimize widget rebuilds
- Use
finalfor variables that won't change - Leverage lazy loading and caching
Development Productivity
- Use hot reload in Flutter
- Utilize code generation tools
- Implement proper error handling
- Write unit and widget tests
Testing
dart
12345678import 'package:test/test.dart'; void main() { test('Addition test', () { expect(1 + 1, equals(2)); }); }
Resources for Further Learning
Continue Learning
Discover more cheatsheets to boost your productivity