Dart 2 Cheat Sheet and Quick Reference: Main Function Operators
Dart 2 Cheat Sheet and Quick Reference: Main Function Operators
Source: raywenderlich.com. Visit for more Flutter/Dart resources and tutorials! Version 1.0.1. Copyright 2019 Razeware LLC. All rights reserved.
Page 1
! of 4
Dart 2 Cheat Sheet and Quick Reference
Control Flow: While loops Functions Anonymous Functions and
var i = 1; // Named function Closures
// while, print 1 to 9 bool isBanana(String fruit) { // Anonymous functions (without a name)
while (i < 10) { return fruit == 'banana'; // Assign anonymous function to a variable
print(i); } var multiply = (int a, int b) {
i++; var fruit = 'apple'; return a * b;
} isBanana(fruit); // false }
// do while, print 1 to 9 // Optional parameters with square brackets // Call a function variable
i = 1; String fullName(String first, String last, [String multiply(14, 3); // 42
do { title]) { // Closures
print(i); return "${title == null ? "" : "$title "}$first Function applyMultiplier(num multiplier){
++i; $last"; // Return value has access to multiplier
} while (i < 10); } return (num value) => value * multiplier;
// break at 5 fullName("Ray", "Wenderlich"); // Ray Wenderlich }
do { fullName("Albert", "Einstein", "Professor"); // var triple = applyMultiplier(3);
print(i); Professor Albert Einstein triple(14.0); // 42.0
if (i == 5) { // Optional named arguments with braces
break; bool withinTolerance(
Collections: Lists
} int value, {int min, int max}) {
// Fixed-size list
++i; return (min ?? 0) <= value && value <= (max ??
var pastries = List<String>(3);
} while (i < 10); 10);
// Element access by index
}
pastries[0] = 'cookies';
withinTolerance(11, max: 10, min: 1); // false
pastries[1] = 'cupcakes';
Control Flow: For loops // Default values
pastries[2] = 'donuts';
var sum = 0; bool withinTolerance(
// Growable list
// Init; condition; action for loop int value, {int min = 0, int max = 10}) {
List<String> desserts = [];
for (var i = 1; i <= 10; i++) { return min <= value && value <= max;
desserts.add('cookies');
sum += i; }
// Initialize by growable list
} withinTolerance(5); // true
var desserts = ['cookies', 'cupcakes', 'pie'];
// for-in loop for list // Function as parameter
// List properties and methods
var numbers = [1, 2, 3, 4]; int applyTo(int value, int Function(int) op) {
desserts.length; // 3
for (var number in numbers) { return op(value);
desserts.first; // 'cookies'
print(number); }
desserts.last; // 'pie'
} int square(int n) {
desserts.isEmpty; // false
// Skip over 3 with continue return n * n;
desserts.isNotEmpty; // true
for (var number in numbers) { }
desserts.firstWhere((str) => str.length < 4));
if (number == 3) { applyTo(3, square); // 9
// pie
continue; // Arrow syntax for one line functions
// Collection if
} int multiply(int a, int b) => a * b;
var peanutAllergy = true;
print(number); multiply(14, 3); // 42
var candy = [
} 'junior mints',
// forEach with function argument 'twizzlers',
numbers.forEach(print); // 1, 2, 3, 4 on separate if (!peanutAllergy) 'reeses'
lines ];
// forEach with anonymous function argument // Collection for
numbers = [13, 14, 15, 16]; var numbers = [1, 2, 3];
numbers.forEach( var doubledNumbers =
(number) => print(number.toRadixString(16)); [for (var number in numbers) 2 * number];
// d, e, f, 10 // [2, 4, 6]
Source: raywenderlich.com. Visit for more Flutter/Dart resources and tutorials! Version 1.0.1. Copyright 2019 Razeware LLC. All rights reserved.
Page 2
! of 4
Dart 2 Cheat Sheet and Quick Reference
Collections: List Operations // Element access by key filmography.add('Upcoming $franchiseName
// Spread Operator and null-spread operator var ironManPower = avengers["Iron Man"]; // Suit sequel');
var pastries = ['cookies', 'cupcakes']; avengers.containsKey("Captain America"); // true }
var desserts = ['donuts', ...pastries, ...?candy]; avengers.containsValue("Arrows"); // false
// Map to transform list // Access all keys and values // Override from Object
var numbers = [1, 2, 3, 4]; avengers.keys.forEach(print); // Iron Man, Captain String toString() =>
var squares = numbers.map( America, Thor "${[name, ...filmography].join("\n- ")}\n";
(number) => number * number).toList(); avengers.values.forEach(print); // Suit, Shield, }
// [1, 4, 9, 16] Hammer
// Filter list using where // Loop over key-value pairs var gotgStar = Actor('Zoe Saldana', []);
var evens = squares.where( avengers.forEach((key, value) => print('$key -> gotgStar.name = 'Zoe Saldana';
(square) => square.isEven); // (4, 16) $value')); gotgStar.filmography.add('Guardians of the Galaxy');
// Reduce list to combined value gotgStar.debut = 'Center Stage';
var amounts = [199, 299, 299, 199, 499]; print(Actor.rey().debut); // The Force Awakens
var total = amounts.reduce( var kit = Actor.gameOfThrones('Kit Harington');
(value, element) => value + element); // 1495 var star = Actor.inTraining('Super Star');
Classes and Objects // Cascade syntax ..
class Actor { gotgStar // Get an object
// Properties ..name = 'Zoe' // Use property
..signOnForSequel('Star Trek'); // Call method
Collections: Sets String name;
// Create set of int var filmography = <String>[];
var someSet = <int>{};
// Set type inference // Short-form constructor
var anotherSet = {1, 2, 3, 1}; Actor(this.name, this.filmography); Static Class Members
// Check for element enum PhysicistType { theoretical, experimental, both
anotherSet.contains(1); // true // Named constructor }
anotherSet.contains(99); // false Actor.rey({this.name = "Daisy Ridley"}) { class Physicist {
// Adding and removing elements filmography = ['The Force Awakens', 'Murder on String name;
someSet.add(42); the Orient Express']; PhysicistType type;
someSet.add(2112); } // Internal constructor
someSet.remove(2112); Physicist._internal(this.name, this.type);
// Add to set from list // Calling other constructors // Static property
someSet.addAll([1, 2, 3, 4]); Actor.inTraining(String name) : this(name, []); static var physicistCount = 0;
// Intersection // Static method
var intersection = someSet.intersection(anotherSet); // Constructor with initializer list static Physicist newPhysicist(
// Union Actor.gameOfThrones(String name) String name,
var union = someSet.union(anotherSet); : this.name = name, this.filmography = ['Game PhysicistType type) {
of Thrones'] { physicistCount++;
print('My name is ${this.name}'); return Physicist._internal(name, type);
} }
}
// Getters and Setters
Collections: Maps String get debut => '$name debuted in $
// Map from String to int {filmography.first}'; final emmy = Physicist.newPhysicist(
var emptyMap = Map<String, int>(); set debut(String value) => filmography.insert(0, "Emmy Noether", PhysicistType.theoretical);
// Map from String to String value); final lise = Physicist.newPhysicist(
var avengers = { "Lise Meitner", PhysicistType.experimental);
"Iron Man": "Suit", "Captain America": "Shield", // Methods print(Physicist.physicistCount); // 2
"Thor": "Hammer"}; void signOnForSequel(String franchiseName) {
Source: raywenderlich.com. Visit for more Flutter/Dart resources and tutorials! Version 1.0.1. Copyright 2019 Razeware LLC. All rights reserved.
Page 3
! of 4
Dart 2 Cheat Sheet and Quick Reference
Class Inheritance Abstract Classes, Interfaces, Mixins // var snake = Animal(); // error: can't instantiate
// Base aka parent class enum BloodType { warm, cold } abstract class
class Person { abstract class Animal { // Can instantiate concrete classes
// Parent properties inherited by child BloodType bloodType; // Base class property var garfield = Cat();
String firstName; void goSwimming(); // Abstract method without var flipper = Dolphin(4.0);
String lastName; implementation var snake = Reptile();
// Parent class constructor } // Call concrete methods
Person(this.firstName, this.lastName); mixin Milk { flipper.goSwimming(); // Click! Click!
// Parent class method bool hasMilk; garfield.goSwimming(); // No thanks!
String get fullName => '$firstName $lastName'; bool doIHaveMilk() => hasMilk; // Use interface implementation
// Optional @override annotation } var orca = Dolphin(8.0); var alpha = Dolphin(5.0);
// All class hierarchies and types have Object as // Concrete class inheriting from abstract class var dolphins = [alpha, orca, flipper];
root class class Cat extends Animal with Milk { dolphins.sort();
@override BloodType bloodType = BloodType.warm; // Set value print(dolphins); // [4 meters, 5 meters, 8 meters]
String toString() => fullName; for property print(snake.doIHaveMilk()); // false
} Cat() { hasMilk = true; } // Set mixin property print(garfield.doIHaveMilk()); // true
// Subclass aka child class // Concrete subclass must implement abstract
class Student extends Person { methods
// Properties specific to child @override
var grades = <String>[]; void goSwimming() { print("No thanks!"); }
// Call super on parent constructor }
Student(String firstName, String lastName) // Concrete class that also implements Comparable
: super(firstName, lastName); interface
// Optional override annotation on parent method class Dolphin extends Animal implements
override Comparable<Dolphin> {
@override BloodType bloodType = BloodType.warm;
String get fullName => '$lastName, $firstName'; double length; // Concrete sublcass property
} Dolphin(this.length); // Concrete subclass
final jon = Person('Jon', 'Snow'); constructor
final jane = Student('Jane', 'Snow'); // Calls // Concrete subclass must implement abstract
parent constructor methods
print(jon); // Jon Snow @override
// Use toString in parent, in turn using subclass void goSwimming() { print("Click! Click!"); }
override of fullName // Also must implement interface methods
print(jane); // Snow, Jane @override
int compareTo(other) =>
length.compareTo(other.length);
@override
String toString() => '$length meters';
}
class Reptile extends Animal with Milk {
BloodType bloodType = BloodType.cold;
Reptile() { hasMilk = false; }
@override
void goSwimming() { print("Sure!"); }
}
Source: raywenderlich.com. Visit for more Flutter/Dart resources and tutorials! Version 1.0.1. Copyright 2019 Razeware LLC. All rights reserved.
Page 4
! of 4