0% found this document useful (0 votes)
321 views4 pages

Dart 2 Cheat Sheet and Quick Reference: Main Function Operators

Uploaded by

JOSE TOKIKA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
321 views4 pages

Dart 2 Cheat Sheet and Quick Reference: Main Function Operators

Uploaded by

JOSE TOKIKA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Dart 2 Cheat Sheet and Quick Reference

main function Operators I'm not creating the universe.


void main() { // Arithmetic I'm creating a model of the universe,
print("Hello, Dart!"); 40 + 2; // 42 which may or may not be true.""";
} 44 - 2; // 42 // Raw string with r prefix
21 * 2; // 42 var rawString =r”I'll\nbe\nback!";
// prints I’ll\nbe\nback!
Variables, Data Types, & Comments 84 / 2; // 42
// Use var with type inference or instead use type 84.5 ~/ 2.0; // int value 42
name directly 392 % 50; // 42
var myAge = 35; // inferred int created with var // Types can be implicitly converted Control Flow: Conditionals
var pi = 3.14; // inferred double created with var var answer = 84.0 / 2; // int 2 to double var animal = 'fox';
int yourAge = 27; // type name instead of var // Equality and Inequality if (animal == 'cat' || animal == 'dog') {
double e = 2.718; // type name instead of var 42 == 43; // false print('Animal is a house pet.');
// This is a comment 42 != 43; // true } else if (animal == 'rhino') {
print(myAge); // This is also a comment. // Increment and decrement print('That\'s a big animal.');
/* print(answer++); // 42, since it prints first for } else {
And so is this. postfix print('Animal is NOT a house pet.');
*/ print(--answer); // 42, since it decrements first }
// dynamic can have value of any type for prefix // switch statement
dynamic numberOfKittens; // Comparison enum Semester { fall, spring, summer }
// dynamic String 42 < 43; // true Semester semester;
numberOfKittens = 'There are no kittens!'; 42 > 43; // false switch (month) {
numberOfKittens = 0; // dynamic int 42 <= 43; // true case Month.august:
numberOfKittens = 1.0; // dynamic double 42 >= 43; // false case Month.september:
bool areThereKittens = true; // bool // Compound assignment case Month.october:
// Compile-time constants answer += 1; // 43 case Month.november:
const speedOfLight = 299792458; answer -= 1; // 42 case Month.december:
// Immutables with final answer *= 2; // 84 semester = Semester.fall;
final planet = 'Jupiter'; answer /= 2; // 42 break;
// planet = 'Mars'; // error: planet is immutable // Logical case Month.january:
// Enumerations (41 < answer) && (answer < 43); // true case Month.february:
enum Month { january, february, march, april, may, (41 < answer) || (answer > 43); // true case Month.march:
june, july, august, september, october, november, !(41 < answer)); // false case Month.april:
december case Month.may:
} semester = Semester.spring;
break;
final month = Month.august; Strings
case Month.june:
// Can use single or double quotes for String type
case Month.july:
var firstName = 'Albert';
Null semester = Semester.summer;
String lastName = "Einstein";
int age; // initialized to null break;
// Embed variables in Strings with $
double height; }
var physicist = "$firstName $lastName”;
String err; // Albert Einstein
// Check for null // Escape sequences such as \' and \n
var error = err ?? "No error"; // No error // and concatenating adjacent strings
// Null-check compound assignment var quote = 'If you can\'t' ' explain it simply\n'
err ??= error; "you don't understand it well enough.";
// Null-check on property access // Concatenation with +
print(age?.isEven); var energy = "Mass" + " times " + "c squared";
// Preserving formatting with """
var model = """

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

You might also like