Dart Cheatsheet-1.0.3
Dart Cheatsheet-1.0.3
Strings
var error = err ?? 'No error'; // No error
void main() { // Null-check compound assignment // Can use double or single quotes
print('Hello, Dart!'); err ??= error; // for String type
} // Null-aware operator(?.) for property access var firstName = 'Albert';
print(err?.toUpperCase()); String lastName = "Einstein";
Variables, Data Types & Comments err!.length; // '!' casts err to non-nullable // You can interpolate variables in
// strings with $
var fullName = '$firstName $lastName';
// Use var with type inference or use type
// Strings support special characters(\n, \t, etc)
// directly
Operators print('Name:\t$fullName');
var myAge = 35; //inferred int created with var // Name: Albert Einstein
var pi = 3.14; // inferred double created with var // Concatenate adjacent strings
// --- Arithmetic ---
int yourAge = 27; // type name instead of var var quote = 'If you can\'t explain it simply\n'
40 + 2; // 42
// dynamic can have value of any type "you don't understand it well enough.";
dynamic numberOfKittens;
44 - 2; // 42 // Concatenate with +
// dynamic String 21 * 2; // 42 var energy = "Mass" + ' times ' + "c squared";
numberOfKittens = 'There are no kittens!'; 84 / 2; // 42 // Preserving formatting with """
numberOfKittens = 0; // dynamic int 84.5 ~/ 2.0; // int value 42 var model = """I'm not creating the universe.
bool areThereKittens = true; // bool 392 % 50; // 42 I'm creating a model of the universe,
// Types can be implicitly converted which my or may not be true.""";
// Compile-time constants
var answer = 84.0 / 2; // int 2 to double // Raw string with r prefix
const speedOfLight = 299792458; var rawString = "I'll\nbe\nback!";
// Immutables with final // --- Equality and Inequality ---
// I'll\nbe\nback!
final planet = 'Jupiter'; 42 == 43; // false
// planet = 'Mars'; // error: planet is immutable 42 != 43; // true
late double defineMeLater; // late variables // --- Increment and Decrement ---
// --- Comments --- print(answer++); // 42, prints first Control Flow: Conditionals
// This is a comment print(--answer); // 42, decrements first
print(myAge); // This is also a comment // --- Comparison --- var animal = 'fox';
/* 42 < 43; // true if (animal == 'cat' || animal == 'dog') {
And so is this, spanning 42 > 43; // false print('Animal is a house pet.');
multiple lines 42 <= 43; // true } else if (animal == 'rhino') {
*/ 42 >= 43; // false print('That\'s a big animal.');
/// This is a doc comment // --- Compound assignment --- } else {
// --- Simple enums --- answer += 1; // 43 print('Animal is NOT a house pet.');
enum Direction { answer -= 1; // 42 }
north, south, east, west answer *= 2; // 84 // switch statement
} answer /= 2; // 42 switch (animal) {
final sunset = Direction.west; // --- Logical --- case 'cat':
(41 < answer) && (answer < 43); // true case 'dog':
(41 < answer) || (answer > 43); // true print('Animal is a house pet.');
!(41 < answer); // false break;
Nullables and Non-nullables case 'rhino':
// Conditional/ternary operator
print('That\'s a big animal.');
// Non-nullable, can't be used until assigned var error = err == null
break;
int age; ? 'No error': err; // No error
default:
print(age); // error: must be assigned before use
print('Animal is NOT a house pet.');
double? height; // null by default
}
print(height); // null
String? err;
Control Flow: While Loops Functions // Closures
Function applyMultiplier(num multiplier) {
var i = 1; // Named function return (num value) => value * multiplier;
// while, print 1 to 9 bool isTeen(int age) { }
while (i < 10) { return age > 12 && age < 20;
print(i); }
var triple = applyMultiplier(3);
i++; const myAge = 19; triple(14.0); // 42.0
} print(isTeen(myAge)); // true
// do while, print 1 to 9 // Arrow syntax for one line functions
do { int multiply(int a, int b) => a * b;
print(i); Collections: Lists
multiply(14, 3); // 42
++i; // Optional positional parameters
} while (i < 10); // Fixed-size list of 3, filled with empty
String titledName(
// break at 5 // values
String name, [String? title]) {
do { var pastries = List.filled(3, '');
return '${title ?? ''} $name';
print(i); // List assignment using index
}
if (i == 5) { pastries[0] = 'cookies';
titledName('Albert Einstein');
break; pastries[1] = 'cupcakes';
// Albert Einstein
} titledName('Albert Einstein', 'Prof');
pastries[2] = 'donuts';
++i;
// Prof Albert Einstein // Empty, growable list
} while (i < 10); List<String> desserts = [];
// Named & function parameters
int applyTo( var desserts
int Function(int) op, = List<String>.empty(growable: true);
{required int number}) { desserts.add('cookies');
Control Flow: For Loops return op(number); // Growable list literals
} var desserts = ['cookies', 'cupcakes', 'pie'];
var sum = 0; int square(int n) => n * n; // List properties
// Init; condition; action for loop applyTo(number: 3, square); // 9 desserts.length; // 3
for (var i = 1; i <= 10; i++) { // Optional named & default parameters desserts.first; // 'cookies'
sum += i; bool withinTolerance( desserts.last; // 'pie'
} int value, {int min = 0, int? max}) { desserts.isEmpty; // false
// for-in loop for list return min <= value && desserts.isNotEmpty; // true
var numbers = [1, 2, 3, 4]; value <= (max ?? 10); desserts.firstWhere((str) => str.length < 4);
for (var number in numbers) { } // pie
withinTolerance(5); // true // Collection if
print(number);
var peanutAllergy = true;
}
List<String>? candy;
// Skip over 3 with continue candy = [
for (var number in numbers) { 'junior mints',
if (number == 3) { Anonymous Functions 'twizzlers',
continue; if (!peanutAllergy) 'reeses'
} // Assign anonymous function to a variable ];
print(number); // Collection for
var multiply = (int a, int b) => a * b;
} var numbers = [1, 2, 3];
// forEach // Call the function variable var doubleNumbers = [
numbers.forEach(print); multiply(14, 3); // 42 for (var number in numbers) 2 * number
]; //[2, 4, 6]
Collections: Lists Operations // Map from String to String // Methods
final avengers = { void signOnForSequel(String franchiseName) {
// Spread and null-spread operators 'Iron Man': 'Suit', filmography.add('Upcoming $franchiseName sequel');
'Captain America': 'Shield', 'Thor': 'Hammer' }
var pastries = ['cookies', 'cupcakes'];
}; // Override from Object
var desserts = ['donuts', ...pastries, ...?candy]; // Element access by key String toString()
// Using map to transform lists final ironManPower = avengers['Iron Man']; // Suit => '${[name, ...filmography].join('\n- ')}\n';
final squares = numbers.map( avengers.containsKey('Captain America'); // true }
(number) => number * number) avengers.containsValue('Arrows'); // false var gotgStar = Actor('Zoe Saldana', []);
.toList(); // [1, 4, 9] // Access all keys and values gotgStar.name = 'Zoe Saldana';
// Filter list using where avengers.forEach(print); gotgStar.filmography.add('Guardians of the Galaxy');
var evens = squares.where( // Iron Man, Captain America, Thor gotgStar.debut = 'Center Stage';
avengers.values.forEach(print); print(Actor.rey().debut); // The Force Awakens
(number) => number.isEven); // (4)
// Suit, Shield, Hammer var kit = Actor.gameOfThrones('Kit Harington');
// Reduce list to combined value // Loop over key-value pairs
var amounts = [199, 299, 299, 199, 499]; var star = Actor.inTraining('Super Star');
avengers.forEach( // Cascade syntax
var total = amounts.reduce( (key, value) => print('$key -> $value')); gotg // Get an object
(value, element) => value + element); // 1495 ..name == 'Zoe' // Set property
..signOnForSequel('Star Trek'); // Call method
Classes and Objects