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

Dart Cheatsheet-1.0.3

Uploaded by

hyuuks
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)
59 views4 pages

Dart Cheatsheet-1.0.3

Uploaded by

hyuuks
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

main Function // "if null" check

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

Collections: Sets class Actor {


// Properties
Static Class Members & Enhanced Enums
// Create a set of int String name; enum PhysicistType {
var someSet = <int>{}; var filmography = <String>[]; theoretical, experimental, both
// Set type inference // Constructor }
var evenSet = {2, 4, 6, 8}; Actor(this.name, this.filmography); class Physicist {
evenSet.contains(2); // true // Named constructor String name;
Actor.rey({this.name = 'Daisy Ridley'}) { PhysicistType type;
evenSet.contains(99); // false // Internal constructor
filmography = ['The Force Awakens',
// Adding and removing elements Physicist._internal(this.name, this.type);
'Murder on the Orient Express'];
someSet.add(0); // Static property
}
someSet.add(2112); static var physicistCount = 0;
// Calling other constructors // Static method
someSet.remove(2112); Actor.inTraining(String name): this(name, []); static Physicist newPhysicist(
// Add a list to a set String name, PhysicistType type
someSet.addAll([1, 2, 3, 4]); // Constructor with initializer list ) {
someSet.intersection(evenSet); // {2, 4} Actor.gameOfThrones(String name) physicistCount++;
someSet.union(evenSet); // {0, 1, 2, 3, 4, 6, 8} : this.name = name, return Physicist._internal(name, type);
this.filmography = ['Game of Thrones'] { }
}
print('My name is ${this.name}');
// Calling static class members
} final emmy = Physicist.newPhysicist(
Collections: Maps
// Getters and setters 'Emmy Noether', PhysicistType.theoretical);
String get debut final lise = Physicist.newPhysicist(
// Map from String to int
=> '$name debuted in ${filmography.first}'; 'Lise Meitner', PhysicistType.experimental);
final emptyMap = Map<String, int>(); set debut(String value) print(Physicist.physicistCount);
=> filmography.insert(0, value);
// Enhanced enums with members & constructors // Subclass aka child class // Concrete class that also implements
enum Season { class Student extends Person { // Comparable interface
// Call constructor when the enum's created // Properties specific to child class Dolphin extends Animal implements
winter(['December', 'January', 'February']), var grades = <String>[]; Comparable<Dolphin> {
// Pass initializers to parent constructor // Must implement abstract property
spring(['March', 'April', 'May']),
Student(super.firstName, super.lastName); BloodType bloodType = BloodType.cold;
summer(['June', 'July', 'August']),
// Same as: // Class property
autumn(['September', 'October', 'November']);
/** double length;
// Enum property // Concrete subclass constructor
* Student(String firstName, String lastName)
final List<String> months; * : super(firstName, lastName) Dolphin(this.length);
// Constructor */ // Must implement abstract methods
const Season(this.months); @override
// Methods // Optional, override parent method void goSwimming() => print('Click! Click!');
bool get isCold => name == 'winter'; @override // Must also implement interface methods
// Override methods String get fullName => '$lastName, $firstName'; @override
@override } int compareTo(Dolphin other)
String toString() final jon = Person('Jon', 'Snow'); => length.compareTo(other.length);
// Calls parent constructor @override
=> 'Season: $name, months: ${months.join(', ')}';
final jane = Student('Jane', 'Snow'); String toString() => '$length meters';
}
print(jon); // Jon Snow }
final summer = Season.summer; class Reptile extends Animal with Milk {
print(jane); // Snow, Jane
print(summer); // Prints the toString() value BloodType bloodType = BloodType.warm;
print(summer.isCold); // false Reptile() { hasMilk = true; }
@override
void goSwimming() => print('Sure!');
Abstract Classes, Interfaces & Mixins }
// var snake = Animal();
Class Inheritance enum BloodType { warm, cold } // error: can't instantiate abstract class
abstract class Animal { // Can instantiate concrete classes
// Base aka parent class abstract BloodType bloodType; //Abstract Property var garfield = Cat();
class Person { // Abstract method, not implemented var flipper = Dolphin(4.0);
void goSwimming(); var snake = Reptile();
// Properties inherited by child
} // Call concrete methods
String firstName; mixin Milk { flipper.goSwimming(); // Click! Click!
String lastName; bool? hasMilk; garfield.goSwimming(); // No thanks!
// Parent class constructor bool doIHaveMilk() => hasMilk ?? false; // Use interface implementation
Person(this.firstName, this.lastName); } var orca = Dolphin(8.0);
// Concrete class inheriting abstract class var alpha = Dolphin(5.0);
// Parent class method
class Cat extends Animal with Milk { var dolphins = [alpha, orca, flipper];
String get fullName => '$firstName $lastName'; // Set property // Uses length to sort based on compareTo
// Optional, override toString() from Object BloodType bloodType = BloodType.warm; dolphins.sort();
// All classes have Object as root class Cat() { hasMilk = true; } // Set mixin property print(dolphins);
@override // Concrete subclass must implement // [4.0 meters, 5.0 meters, 8.0 meters]
// abstract methods print(snake.doIHaveMilk()); // false
String toString() => fullName;
@override print(garfield.doIHaveMilk()); // true
} void goSwimming() => print('No thanks!');
}

You might also like