Built for developers, by XinhND

v2.1.0

Ready

Dart Cheat Sheet

Complete reference guide for Dart with interactive examples and live playground links

Basic Syntax

Hello World

Basic Dart program structure

Dart
void main() {
  print('Hello, World!');
}

Variables and Data Types

Variable declaration and basic data types

Dart
// Variable declaration
var name = 'Dart';              // Type inference
String language = 'Dart';       // Explicit type
int number = 42;                // Integer
double pi = 3.14159;           // Double
bool isActive = true;           // Boolean
List<String> fruits = ['apple', 'banana'];  // List
Map<String, int> scores = {     // Map
  'Alice': 100,
  'Bob': 90
};

// Constants
const maxValue = 100;
final currentTime = DateTime.now();

// Null safety
String? nullableName;           // Nullable
late String lateName;          // Late initialization

String Operations

Common string operations

Dart
String text = 'Hello World';

// String methods
print(text.length);           // 11
print(text.toUpperCase());    // HELLO WORLD
print(text.toLowerCase());    // hello world
print(text.contains('World')); // true
print(text.replaceAll('World', 'Dart')); // Hello Dart

// String interpolation
String name = 'Dart';
print('Hello, $name!');       // Hello, Dart!
print('Sum: 3');       // Sum: 3

// Multi-line strings
String multiLine = '''
  Line 1
  Line 2
  Line 3
''';

Collections

Working with collections

Dart
// Lists
List<int> numbers = [1, 2, 3, 4, 5];
numbers.add(6);               // Add element
numbers.remove(3);            // Remove element
numbers.length;               // Get length
numbers.first;                // First element
numbers.last;                 // Last element

// Sets
Set<String> fruits = {'apple', 'banana', 'orange'};
fruits.add('mango');          // Add element
fruits.remove('banana');      // Remove element
fruits.contains('apple');     // Check existence

// Maps
Map<String, int> scores = {
  'Alice': 100,
  'Bob': 90
};
scores['Charlie'] = 95;       // Add/update
scores.remove('Bob');         // Remove
scores.containsKey('Alice');  // Check key

Control Structures

Control flow statements

Dart
// If-else
if (age >= 18) {
  print('Adult');
} else if (age >= 13) {
  print('Teenager');
} else {
  print('Child');
}

// Switch
switch (status) {
  case 1:
    print('Active');
    break;
  case 2:
    print('Inactive');
    break;
  default:
    print('Unknown');
}

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

for (var item in items) {
  print(item);
}

while (condition) {
  // Do something
}

do {
  // Do something
} while (condition);

Functions

Function Definition

Different ways to define functions

Dart
// Basic function
int add(int a, int b) {
  return a + b;
}

// Arrow function
int multiply(int a, int b) => a * b;

// Optional parameters
void greet(String name, [String? title]) {
  print('Hello, ${title ?? ''} $name');
}

// Named parameters
void setUser({String? name, int? age}) {
  print('Name: $name, Age: $age');
}

// Default values
void connect({String host = 'localhost', int port = 8080}) {
  print('Connecting to $host:$port');
}

// Function as parameter
void process(Function callback) {
  callback();
}

Async Functions

Asynchronous programming

Dart
// Future
Future<String> fetchData() async {
  await Future.delayed(Duration(seconds: 2));
  return 'Data loaded';
}

// Async/await
void main() async {
  try {
    final data = await fetchData();
    print(data);
  } catch (e) {
    print('Error: $e');
  }
}

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

// Using streams
void main() async {
  await for (final count in countStream()) {
    print(count);
  }
}

Object-Oriented Programming

Classes and Objects

Basic class and object usage

Dart
class Person {
  // Instance variables
  String name;
  int age;
  
  // Constructor
  Person(this.name, this.age);
  
  // Named constructor
  Person.anonymous() : name = 'Anonymous', age = 0;
  
  // Getter
  String get description => '$name is $age years old';
  
  // Setter
  set age(int value) {
    if (value < 0) throw ArgumentError('Age cannot be negative');
    age = value;
  }
  
  // Method
  void greet() {
    print('Hello, I am $name');
  }
}

// Creating objects
final person = Person('Alice', 25);
person.greet();

Inheritance and Interfaces

Inheritance and interfaces

Dart
// Abstract class
abstract class Animal {
  String name;
  Animal(this.name);
  
  void makeSound();
}

// Interface
class Flyable {
  void fly() {
    print('Flying...');
  }
}

// Implementation
class Bird extends Animal implements Flyable {
  Bird(String name) : super(name);
  
  @override
  void makeSound() {
    print('$name says: Tweet!');
  }
  
  @override
  void fly() {
    print('$name is flying');
  }
}

// Using inheritance
final bird = Bird('Sparrow');
bird.makeSound();
bird.fly();

Mixins

Working with mixins

Dart
// Mixin
mixin Logger {
  void log(String message) {
    print('Log: $message');
  }
}

mixin Validator {
  bool isValid(String input) {
    return input.isNotEmpty;
  }
}

// Using mixins
class User with Logger, Validator {
  String name;
  User(this.name);
  
  void updateName(String newName) {
    if (isValid(newName)) {
      name = newName;
      log('Name updated to $newName');
    }
  }
}

// Using the class
final user = User('Alice');
user.updateName('Bob');

Flutter Basics

Widgets

Basic Flutter widgets

Dart
// Stateless widget
class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(16),
      child: Column(
        children: [
          Text('Hello, Flutter!'),
          ElevatedButton(
            onPressed: () {
              print('Button pressed');
            },
            child: Text('Click me'),
          ),
        ],
      ),
    );
  }
}

// Stateful widget
class CounterWidget extends StatefulWidget {
  @override
  _CounterWidgetState createState() => _CounterWidgetState();
}

class _CounterWidgetState extends State<CounterWidget> {
  int count = 0;
  
  void increment() {
    setState(() {
      count++;
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text('Count: $count'),
        ElevatedButton(
          onPressed: increment,
          child: Text('Increment'),
        ),
      ],
    );
  }
}

Navigation

Screen navigation in Flutter

Dart
// Push to new screen
Navigator.push(
  context,
  MaterialPageRoute(
    builder: (context) => SecondScreen(),
  ),
);

// Pop current screen
Navigator.pop(context);

// Push and replace
Navigator.pushReplacement(
  context,
  MaterialPageRoute(
    builder: (context) => NewScreen(),
  ),
);

// Push and remove until
Navigator.pushAndRemoveUntil(
  context,
  MaterialPageRoute(
    builder: (context) => HomeScreen(),
  ),
  (route) => false,
);

State Management

State management with Provider

Dart
// Provider
class CounterProvider extends ChangeNotifier {
  int _count = 0;
  int get count => _count;
  
  void increment() {
    _count++;
    notifyListeners();
  }
}

// Using provider
class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<CounterProvider>(
      builder: (context, counter, child) {
        return Column(
          children: [
            Text('Count: ${counter.count}'),
            ElevatedButton(
              onPressed: counter.increment,
              child: Text('Increment'),
            ),
          ],
        );
      },
    );
  }
}

Dart - Interactive Developer Reference

Hover over code blocks to copy or run in live playground