Dart Cheat Sheet [Advanced] For Flutter Developers

Dart Cheat Sheet Advanced

Written and reviewed by: 

SHARE

Hello Flutter Devs! In this post, I share the Advanced Dart Cheat Sheet. It will help you remember the basic syntax of Dart Programming Language. It will enhance your Flutter development journey.

Table of Contents

Download Dart Cheat Sheet PDF Free

Subscribe to our newsletter to download the PDF for free! We’ll send the PDF straight to your inbox.

Advanced Syntax and Features

Null Safety:

				
					int? nullableInt; // Nullable type
int nonNullableInt = 0;

int? mayReturnNull() => null;
int mustReturnNonNull() => 0;

int value = nullableInt ?? 42; // Null-aware operator
nullableInt ??= 42; // Assign if null
				
			

Collection If and For:

				
					var list = [
  'Alice',
  if (true) 'Bob',
  for (var i in [1, 2, 3]) 'Item $i'
];

var map = {
  'key1': 'value1',
  if (true) 'key2': 'value2',
  for (var i in [1, 2, 3]) 'key$i': 'value$i'
};

				
			

Spread Operator:

				
					var list1 = [1, 2, 3];
var list2 = [0, ...list1, 4, 5];

var set1 = {'a', 'b'};
var set2 = {'c', ...set1, 'd'};


				
			

Extension Methods:

				
					extension StringExtension on String {
  String reverse() => split('').reversed.join('');
}

void main() {
  print('hello'.reverse()); // olleh
}

				
			

Higher-Order Functions:

				
					void execute(Function fn) => fn();

void main() {
  execute(() => print('Hello from higher-order function'));
}


				
			

Advanced Classes and Generics

Abstract Classes and Mixins:

				
					abstract class Animal {
  void makeSound();
}

mixin CanFly {
  void fly() => print('Flying');
}

class Bird extends Animal with CanFly {
  @override
  void makeSound() => print('Chirp');
}

				
			

Generics:

				
					class Box<T> {
  T content;
  Box(this.content);
}

void main() {
  var intBox = Box<int>(123);
  var stringBox = Box<String>('Hello');
}


				
			

Covariance and Contravariance:

				
					class Animal {}
class Dog extends Animal {}

void main() {
  List<Dog> dogs = [];
  List<Animal> animals = dogs; // Covariant
}
				
			

Type Aliases:

				
					typedef IntList = List<int>;

void main() {
  IntList myInts = [1, 2, 3];
}

				
			

Factory Constructors:

				
					class Logger {
  static final Logger _singleton = Logger._internal();
  
  factory Logger() {
    return _singleton;
  }
  
  Logger._internal();
}

				
			

Concurrency and Isolates

Isolate:

				
					import 'dart:isolate';

void entryPoint(SendPort sendPort) {
  sendPort.send('Hello from isolate');
}

void main() async {
  var receivePort = ReceivePort();
  await Isolate.spawn(entryPoint, receivePort.sendPort);

  receivePort.listen((message) {
    print(message);
  });
}

				
			

Streams:

				
					Stream<int> countStream = Stream.periodic(Duration(seconds: 1), (count) => count).take(10);

void main() {
  countStream.listen((count) {
    print(count);
  });
}

				
			

Advanced Error Handling

Custom Exceptions:

				
					class CustomException implements Exception {
  final String message;
  CustomException(this.message);
}

void riskyOperation() {
  throw CustomException('Something went wrong');
}

void main() {
  try {
    riskyOperation();
  } catch (e) {
    print('Caught: $e');
  }
}
				
			

Stack Traces:

				
					void main() {
  try {
    throw Exception('Error');
  } catch (e, stackTrace) {
    print('Caught $e');
    print('Stack trace:\n$stackTrace');
  }
}

				
			

Interoperability

Calling JavaScript from Dart (in Flutter):

				
					import 'dart:js' as js;

void main() {
  js.context.callMethod('alert', ['Hello from Dart!']);
}


				
			

FFI (Foreign Function Interface):

				
					import 'dart:ffi';
import 'package:ffi/ffi.dart';

typedef CFunc = Int32 Function(Int32);
typedef DartFunc = int Function(int);

void main() {
  final dylib = DynamicLibrary.open('path/to/library.so');
  final DartFunc square = dylib
      .lookup<NativeFunction<CFunc>>('square')
      .asFunction<DartFunc>();

  print(square(4)); // 16
}

				
			

Meta Programming

Reflection:

				
					import 'dart:mirrors';

void main() {
  var mirror = reflectClass(MyClass);
  print(mirror.declarations.keys); // Prints all class members
}

class MyClass {
  void myMethod() {}
}


				
			

Annotations:

				
					class MyAnnotation {
  final String description;
  const MyAnnotation(this.description);
}

@MyAnnotation('This is a test class')
class TestClass {}

void main() {
  var mirror = reflectClass(TestClass);
  var metadata = mirror.metadata;
  for (var meta in metadata) {
    if (meta.reflectee is MyAnnotation) {
      print(meta.reflectee.description); // This is a test class
    }
  }
}
				
			

Conclusion:

 
This Advanced Dart cheat sheet covers advanced features such as null safety, collection manipulation, extension methods, higher-order functions, advanced class concepts, concurrency with isolates, streams, advanced error handling, interoperability with JavaScript and native code, and meta-programming techniques like reflection and annotations.

FAQ

Null safety in Dart ensures that variables cannot contain null values unless explicitly declared as nullable. This helps prevent null pointer exceptions at runtime. Nullable types are declared with a question mark, e.g., int? nullableInt.

The spread operator (...) allows you to insert multiple elements into a collection. For example:

var list1 = [1, 2, 3];
var list2 = [0, ...list1, 4, 5];

Extension methods allow you to add new functionality to existing libraries. For example:

extension StringExtension on String {
  String reverse() => split('').reversed.join('');
}

void main() {
  print('hello'.reverse()); // olleh
}
 

This adds a reverse method to the String class.

 

Written and reviewed by

Picture of Muhammad Naeem
Muhammad Naeem
Professional Flutter Developer
Scroll to Top