Dart
This Dart cheatsheet
Dart is a modern, object-oriented programming language developed by Google. It is designed for building high-performance applications across platforms—especially mobile apps using Flutter. Dart compiles to native code for mobile and desktop, and to JavaScript for web apps, making it highly versatile.
Key Features:
- Strongly typed with type inference
- Supports both just-in-time (JIT) and ahead-of-time (AOT) compilation
- Rich standard library
- Asynchronous programming support
- Designed for UI development with Flutter
Example:
void main() { print('Hello, Dart!'); }
1. Basics
Variables & Constants
Variables store data. Dart uses var, final, and const.
- var allows reassignment.
- final is assigned once and cannot be changed.
- const is compile-time constant.
Example:
var name = 'Hacker Bytez'; final age = 25; const pi = 3.14159;
Data Types
Dart has built-in types like int, double, String, bool, and List.
Example:
int score = 100; double rating = 4.5; String message = 'Welcome'; bool isLoggedIn = true;
Operators
Includes arithmetic (+, -, *, /), comparison (==, !=, <, >), and logical (&&, ||, !).
Example:
int a = 10, b = 5; print(a + b); // 15 print(a > b); // true
Conditional Statements
Used for decision-making: if, else, switch.
Example:
if (score > 90) { print('Excellent'); } else { print('Keep trying'); }
Loops
Used for iteration: for, while, do-while, for-in.
Example:
for (int i = 0; i < 5; i++) { print('Count: $i'); }
2. Functions
Defining & Calling Functions
Functions encapsulate logic.
Example:
int add(int a, int b) { return a + b; } print(add(2, 3)); // 5
Optional & Named Parameters
Parameters can be optional or named for flexibility.
Example:
void greet(String name, {String? message}) { print('$message, $name'); } greet('Hacker Bytez', message: 'Hello');
Arrow Functions
Concise syntax for single-expression functions.
Example:
int square(int x) => x * x;
Higher-order Functions
Functions that take or return other functions.
Example:
void apply(Function fn, int value) { print(fn(value)); } apply((x) => x * 2, 5); // 10
3. Object-Oriented Programming
Classes & Objects
Encapsulate data and behavior.
Example:
class Person { String name; Person(this.name); void greet() => print('Hi, I am $name'); } Person p = Person('Hacker Bytez'); p.greet();
Inheritance
Allows a class to inherit from another.
Example:
class Animal { void speak() => print('Animal sound'); } class Dog extends Animal { void speak() => print('Bark'); }
Interfaces
Any class can act as an interface.
Example:
class Printable { void printData(); } class Document implements Printable { void printData() => print('Document printed'); }
Abstract Classes
Cannot be instantiated, used for defining interfaces.
Example:
abstract class Shape { void draw(); } class Circle extends Shape { void draw() => print('Drawing Circle'); }
Constructors
Special methods to initialize objects.
Example:
class User { String name; User(this.name); }
Mixins
Used to reuse code across multiple classes.
Example:
mixin Logger { void log(String msg) => print('Log: $msg'); } class Service with Logger {}
4. Advanced Dart
Collections: List, Set, Map
Used to store multiple values.
Example:
List<int> numbers = [1, 2, 3]; Set<String> tags = {'flutter', 'dart'}; Map<String, int> scores = {'Alice': 90, 'Bob': 85};
Enums
Define a fixed set of constants.
Example:
enum Status { success, failure, loading }
Exception Handling
Use try, catch, finally to handle errors.
Example:
try { int result = 10 ~/ 0; } catch (e) { print('Error: $e'); }
Generics
Enable type-safe reusable code.
Example:
List<String> names = ['A', 'B'];
Typedefs
Alias for function types.
Example:
typedef IntOperation = int Function(int a, int b);
5. Asynchronous Programming
Future & async/await
Handle asynchronous operations.
Example:
Future<String> fetchData() async { return 'Data loaded'; }
Streams
Handle continuous data events.
Example:
Stream<int> counter() async* { for (int i = 0; i < 3; i++) { yield i; } }
Error Handling with Futures & Streams
Use catchError or try-catch in async functions.
6. File & Directory Operations
Reading/Writing Files
Use dart:io for file operations.
Example:
import 'dart:io'; void writeFile() { File('example.txt').writeAsStringSync('Hello Dart'); }
Directory Traversal
List files and directories.
Example:
Directory dir = Directory.current; dir.listSync().forEach((f) => print(f.path));
7. Testing
Unit Testing
Test individual functions or classes.
Example:
import 'package:test/test.dart'; void main() { test('Addition test', () { expect(2 + 3, equals(5)); }); }
Integration Testing
Test complete workflows or UI interactions, typically in Flutter apps.
8. Security & Best Practices
Null Safety
Avoid null-related errors by enforcing non-nullable types.
Example:
String name = 'Hacker Bytez'; // Cannot be null
Immutable Data
Use final or const to prevent changes.
Error Handling
Always handle exceptions gracefully to prevent crashes.
Code Style Guidelines
Follow Dart's style guide: consistent naming, indentation, and documentation.