Dart: Operators Cheat Sheet

# Arithmetic Operators
+Add
-Subtract
-exprUnary minus, also known as negation (reverse the sign of the expression)
*Multiply
/Divide
~/Divide, returning an integer result
%Get the remainder of an integer division (modulo)
++Increment
--Decrement
# Equality and Relational Operators
<A Lesser than B(A < B) is True
>=A Greater than or equal to B(A >= B) is False
<=A Lesser than or equal to B(A <= B) is True
==A Equality B(A==B) is False
!=A Not equal B(A!=B) is True
# Type test Operators
isTrue if the object has the specified type
is!False if the object has the specified type
Bitwise ANDa & b
Bitwise ORa | b
Bitwise XORa ^ b
Bitwise NOT~ a
Left shifta ≪ b
Signpropagating right shifta ≫ b
# Assignment Operators
=(Simple Assignment )Assigns values from the right side operand to the left side operand
Ex:C = A + B will assign the value of A + B into C
??=Assign the value only if the variable is null
+=(Add and Assignment)It adds the right operand to the left operand and assigns the result to the left operand.
Ex: C += A is equivalent to C = C + A
-=(Subtract and Assignment)It subtracts the right operand from the left operand and assigns the result to the left operand.
Ex: C -= A is equivalent to C = C – A
*=(Multiply and Assignment)It multiplies the right operand with the left operand and assigns the result to the left operand.
Ex: C *= A is equivalent to C = C * A
/=(Divide and Assignment)It divides the left operand with the right operand and assigns the result to the left operand.
# Logical Operators
&&And − The operator returns true only if all the expressions specified return true
||OR − The operator returns true if at least one of the expressions specified return true
!NOT − The operator returns the inverse of the expression’s result.

Dart: Loops Cheat Sheet

# for Loop

for (initial_count_value; termination-condition; step) { 
   //statements 
} 

Example

void main() { 
   for(var temp, i = 0, j = 1; j<30; temp = i, i = j, j = i + temp) { 
      print('${j}'); 
   } 
} 

=> output

1 
1 
2 
3 
5
8 
13 
21

# for-in Loop

for (variablename in object){  
   statement or block to execute  
}

Example

void main() { 
   var obj = [1,2,3]; 
   
   for (var prop in obj) { 
      print(prop); 
   } 
} 

=> output

1
2
3

# while Loop

while (expression) {
   Statement(s) to be executed if expression is true  
}

Example

void main() { 
   var num = 4; 
   var factorial = 1; 
   
   while(num >=1) { 
      factorial = factorial * num; 
      num--; 
   } 
   print("The factorial  is ${factorial}"); 
}  
The factorial is 24

Dart: Decision Making Cheat Sheet

# If Statement

if(boolean_expression){ 
   // statement(s) will execute if the boolean expression is true. 
} 

Example

void main() { 
   var  num=15; 
   if (num>0) { 
      print("number is positive"); 
   }    
}

=> output

number is positive 

# If Else Statement

if(boolean_expression){ 
   // statement(s) will execute if the Boolean expression is true. 
} else { 
   // statement(s) will execute if the Boolean expression is false. 
} 

Example

void main() { 
   var num = 21; 
   if (num % 2==0) { 
      print("Even"); 
   } else { 
      print("Odd"); 
   } 
}

=> output

Odd

# If Else Ladder

if (boolean_expression1) { 
   //statements if the expression1 evaluates to true 
} 
else if (boolean_expression2) { 
   //statements if the expression2 evaluates to true 
} 
else { 
   //statements if both expression1 and expression2 result to false 
} 

Example

void main() { 
   var num = 20; 
   if(num > 0) { 
      print("${num} is positive"); 
   } 
   else if(num < 0) { 
      print("${num} is negative"); 
   } else { 
      print("${num} is neither positive nor negative"); 
   } 
}  

=> output

20 is positive

# Switch Case Statement

switch(variable_expression) { 
   case constant_expr1: { 
      // statements; 
   } 
   break; 
  
   case constant_expr2: { 
      //statements; 
   } 
   break; 
      
   default: { 
      //statements;  
   }
   break; 
} 

Example

void main() { 
   var grade = "A"; 
   switch(grade) { 
      case "A": {  print("Excellent"); } 
      break; 
     
      case "B": {  print("Good"); } 
      break; 
     
      case "C": {  print("Fair"); } 
      break; 
     
      case "D": {  print("Poor"); } 
      break; 
     
      default: { print("Invalid choice"); } 
      break; 
   } 
}  

=> output

Excellent

Dart: Numbers Cheat Sheet

int var_name;      // declares an integer variable 
double var_name;   // declares a double variable 
void main() {
   // declare an integer
   int num1 = 30;             
     
   // declare a double value
   double num2 = 30.50;  

   // print the values
   print(num1);
   print(num2);
}

=> output

30
30.5

# parse()

void main() { 
   print(num.parse('20')); 
   print(num.parse('20.45')); 
}

=> output

20
20.45

Dart: String Cheat Sheet

String  variable_name = 'value'  

//OR  

String  variable_name = ''value''  

//OR  

String  variable_name = '''line1 
line2'''  

//OR  

String  variable_name= """line1 
line2"""

Example

void main() { 
   String str1 = 'hello'; 
   String str2 = "hello"; 
   String str3 = '''hello world'''; 
   String str4 = """hello world"""; 
   
   print(str1);
   print(str2); 
   print(str3); 
   print(str4); 
}

It will produce the following Output −

hello 
hello 
hello world 
hello world 

# String Interpolation

void main() { 
   String str1 = "hello"; 
   String str2 = "world"; 
   String res = str1 +str2; 
   
   print("The concatenated string : ${res}"); 
}

=> output

The concatenated string : Hello world

Dart: Boolean Cheat Sheet

bool var_name = true;  
OR  
bool var_name = false 

Example

void main() { 
   bool test; 
   test = 12 > 5; 
   print(test); 
}

=> output

true 

Dart: List Cheat Sheet

# first Method

List.first
void main() { 
   var lst = new List(); 
   lst.add(5); 
   lst.add(10); 
   print("The first element of the list is: ${lst.first}"); 
}  

=> output

The first element of the list is: 5  

# isEmpty Method

List.isEmpty
void main() { 
   var lst = new List(); 
   lst.add(5); 
   lst.add(10); 
   print(lst.isEmpty); 
}  

=> output

False  

# isNotEmpty Method

List.isNotEmpty
void main() { 
   var lst = new List(); 
   lst.add(5); 
   lst.add(10); 
   print(lst.isNotEmpty); 
}  

=> output

true  

# length Method

List.length 
void main() { 
   var lst = new List(); 
   lst.add(5); 
   lst.add(10); 
   print("The length of the list is : ${lst.length}"); 
}   

=> output

The length of the list is : 2  

# last Method

List.last 
void main() { 
   var lst = new List(); 
   lst.add(5); 
   lst.add(10); 
   print("The last element of the list is: ${lst.last}"); 
}   

=> output

The last element of the list is: 10 

# reversed Method

List.reversed 
void main() { 
   var lst = new List(); 
   lst.add(5); 
   lst.add(10); 
   print("The list values in reverse order: ${lst.reversed}"); 
}  

=> output

The list values in reverse order: (10, 5)

# single Method

List.single 
void main() { 
   var lst = new List(); 
   lst.add(5);
   print("The list has only one element: ${lst.single}"); 
}  

It will produce the following output −

The list has only one element: 5 

Dart: Symbol Cheat Sheet

Symbol obj = new Symbol('name');  
// expects a name of class or function or library to reflect 
# Foo.dart
library foo_lib;   
// libarary name can be a symbol   

class Foo {         
   // class name can be a symbol  
   m1() {        
      // method name can be a symbol 
      print("Inside m1"); 
   } 
   m2() { 
      print("Inside m2"); 
   } 
   m3() { 
      print("Inside m3"); 
   } 
}
# FooSymbol.dart
import 'dart:core'; 
import 'dart:mirrors'; 
import 'Foo.dart';  

main() { 
   Symbol lib = new Symbol("foo_lib");   
   //library name stored as Symbol 
   
   Symbol clsToSearch = new Symbol("Foo");  
   // class name stored as Symbol  
   
   if(checkIf_classAvailableInlibrary(lib, clsToSearch))  
   // searches Foo class in foo_lib library 
      print("class found.."); 
}  
   
bool checkIf_classAvailableInlibrary(Symbol libraryName, Symbol className) { 
   MirrorSystem mirrorSystem = currentMirrorSystem(); 
   LibraryMirror libMirror = mirrorSystem.findLibrary(libraryName); 
      
   if (libMirror != null) { 
      print("Found Library"); 
      print("checkng...class details.."); 
      print("No of classes found is : ${libMirror.declarations.length}"); 
      libMirror.declarations.forEach((s, d) => print(s));  
         
      if (libMirror.declarations.containsKey(className)) return true; 
      return false; 
   } 
}

=> output

Found Library 
checkng...class details.. 
No of classes found is : 1 
Symbol("Foo") // class name displayed as symbol  
class found. 
# Convert Symbol to String
import 'dart:mirrors'; 
void main(){ 
   Symbol lib = new Symbol("foo_lib"); 
   String name_of_lib = MirrorSystem.getName(lib); 
   
   print(lib); 
   print(name_of_lib); 
}

=> output

Symbol("foo_lib")   

foo_lib     

Dart: Runes Cheat Sheet

# String.codeUnitAt() Function

String.codeUnitAt(int index);

 Returns the 16-bit UTF-16 code unit at the given index.

Example

import 'dart:core'; 
void main(){ 
   f1(); 
} 
f1() { 
   String x = 'Runes'; 
   print(x.codeUnitAt(0)); 
}

=> output

82

# String.codeUnits Property

This property returns an unmodifiable list of the UTF-16 code units of the specified string.

String. codeUnits;

Example

import 'dart:core';  
void main(){ 
   f1(); 
}  
f1() { 
   String x = 'Runes'; 
   print(x.codeUnits); 
} 

=> output

[82, 117, 110, 101, 115]

# String.runes Property

This property returns an iterable of Unicode code-points of this string.Runes extends iterable.

String.runes

Example

void main(){ 
   "A string".runes.forEach((int rune) { 
      var character=new String.fromCharCode(rune); 
      print(character); 
   });  
} 

It will produce the following output −

A 
s 
t 
r 
i 
n 
g

Dart: Enumeration Cheat Sheet

enum enum_name {  
   enumeration list 
}
  • The enum_name specifies the enumeration type name
  • The enumeration list is a comma-separated list of identifiers

Example

enum Status {  
   dog, 
   cat, 
   chicken, 
   duck
}  
void main() { 
   print(Status.values); 
   Status.values.forEach((v) => print('value: $v, index: ${v.index}'));
   print('cat: ${Status.cat}, ${Status.cat.index}'); 
   print('cat index: ${Status.values[1]}'); 
}

=> output

[Status.none, Status.running, Status.stopped, Status.paused] 
value: Status.dog, index: 0 
value: Status.cat, index: 1 
value: Status.chicken, index: 2 
value: Status.duck, index: 3 
cat: Status.cat, 1 
cat index: Status.cat

Dart: Optional Parameters Cheat Sheet

# Optional Positional Parameter

void function_name(param1, [optional_param_1, optional_param_2]) { } 

If an optional parameter is not passed a value, it is set to NULL.

Example

void main() { 
   pos_param(test); 
}  
pos_param(n1,[s1]) { 
   print(n1); 
   print(s1); 
} 

It should produce the following output

test 
null 

# Optional Named Parameter

Declaring the function

void function_name(a, {optional_param1, optional_param2}) { } 

Calling the function

function_name(optional_param:value,…); 

Example

void main() { 
   test_param(i am human); 
   test_param(i am human,s1:'hello'); 
   test_param(i am human,s2:'hello',s1:'world'); 
}  
test_param(n1,{s1,s2}) { 
   print(n1); 
   print(s1); 
}  

It should produce the following output

i am human 
null 
i am human 
hello 
i am human 
world 

# Optional Parameters with Default Values

function_name(param1,{param2= default_value}) { 
   //...... 
} 

Example

void main() { 
   test_param(hello); 
}  
void test_param(n1,{s1:world}) { 
   print(n1); 
   print(s1); 
}   

=> output

hello 
world 

Dart: Functions Cheat Sheet

# Defining a Function

function_name() {  
   //statements      
}

Or

void function_name() { 
   //statements 
}

# Calling a Function

function_name() {
   //statements
}

# Returning Function

return_type function_name(){  
   //statements  
   return value;  
}

# Parameterized Function

Function_name(data_type param_1, data_type param_2[…]) { 
   //statements 
}

Dart: Interfaces Cheat Sheet

class identifier implements interface_name

Example

void main() { 
   ConsolePrinter cp= new ConsolePrinter(); 
   cp.print_data(); 
}  
class Printer { 
   void print_data() { 
      print("This is a cat"); 
   } 
}  
class ConsolePrinter implements Printer { 
   void print_data() {  
      print("This is a dog"); 
   } 
} 

=> output

This is a dog

Implementing Multiple Interfaces

class identifier implements interface-1,interface_2,interface_3, ...

Example

void main() { 
   Calculator c = new Calculator(); 
   print("The gross total : ${c.ret_tot()}"); 
   print("Discount :${c.ret_dis()}"); 
}  
class Calculate_Total { 
   int ret_tot() {} 
}  
class Calculate_Discount { 
   int ret_dis() {} 
}
class Calculator  implements Calculate_Total,Calculate_Discount { 
   int ret_tot() { 
      return 50; 
   } 
   int ret_dis() { 
      return 10; 
   } 
}

=> output

The gross total: 50
Discount:10

Dart: Classes Cheat Sheet

# Declaring a Class
class class_name {  
   <fields> 
   <getters/setters> 
   <constructors> 
   <functions> 
}

A class definition

FieldsA field is any variable declared in a class. Fields represent data pertaining to objects.
Setters and GettersAllows the program to initialize and retrieve the values of the fields of a class. A default getter/ setter is associated with every class. However, the default ones can be overridden by explicitly defining a setter/ getter.
ConstructorsResponsible for allocating memory for the objects of the class.
FunctionsFunctions represent actions an object can take. They are also at times referred to as methods.

Creating Instance of the class

var object_name = new class_name([ arguments ])

Accessing Attributes and Functions

//accessing an attribute 
obj.field_name  

//accessing a function 
obj.function_name()
# Dart Constructors
Class_name(parameter_list) { 
   //constructor body 
}

Named Constructors

Class_name.constructor_name(param_list)
# Dart Class ─ Getters and Setters

Syntax: Defining a getter

Return_type  get identifier 
{ 
} 

Syntax: Defining a setter

set identifier 
{ 
}
# Class Inheritance
class child_class_name extends parent_class_name 

Types of Inheritance

SingleEvery class can at the most extend from one parent class.
Multiple A class can inherit from multiple classes. Dart doesn’t support multiple inheritances.
Multi-levelA class can inherit from another child’s class.

Dart: Collection Queue Cheat Sheet

Identifier = new Queue()

Example

import 'dart:collection'; 
void main() { 
   Queue queue = new Queue(); 
   print("Default implementation ${queue.runtimeType}"); 
   queue.add(10); 
   queue.add(20); 
   queue.add(30); 
   
   for(var no in queue){ 
      print(no); 
   } 
}      

=> output

Default implementation ListQueue
10 
20 
30 

# Adding Multiple Values to a Queue

addAll() function enables adding multiple values to a queue

import 'dart:collection'; 
void main() { 
   Queue queue = new Queue(); 
   print("Default implementation ${queue.runtimeType}"); 
   queue.addAll([10,20,30]); 
   for(var no in queue){ 
      print(no); 
   } 
}

It should produce the following output −

Default implementation ListQueue 
10 
20
30 

# Adding Value at the Beginning and End of a Queue

addFirst(): the method adds the specified value to the beginning of the queue.

import 'dart:collection'; 
void main() { 
   Queue numQ = new Queue(); 
   numQ.addAll([10,20]); 
   print("Printing Q.. ${numQ}");
   numQ.addFirst(30); 
   print("Printing Q.. ${numQ}"); 
}  

=> output

Printing Q.. {10, 20} 
Printing Q.. {30, 10, 20}

addLast(): the function adds the specified object to the end of the queue.

import 'dart:collection'; 
void main() { 
   Queue numQ = new Queue(); 
   numQ.addAll([10,20]); 
   print("Printing Q.. ${numQ}");  
   numQ.addLast(30); 
   print("Printing Q.. ${numQ}"); 
} 

It should produce the following output −

Printing Q.. {10, 20} 
Printing Q.. {10, 20, 30} 

Dart: Object Cheat Sheet

StateDescribes the object. The fields of a class represent the object’s state.
BehaviorDescribes what an object can do.
IdentityA unique value that distinguishes an object from a set of similar other objects. Two or more objects can share the state and behavior but not the identity.

The Cascade operator

Example

class Student { 
   void test_method() { 
      print("This is a  test method"); 
   } 
   
   void test_method1() { 
      print("This is a  test method1"); 
   } 
}  
void main() { 
   new Student() 
   ..test_method() 
   ..test_method1(); 
}

=> output

This is a test method 
This is a test method1

The toString() method

void main() { 
   int n = 12; 
   print(n.toString()); 
} 

=> output

12

Dart: Collection Set Cheat Sheet

Identifier = new Set()

or

Identifier = new Set.from(Iterable)
# HashMap
Identifier= new HashMap()

Example

import 'dart:collection'; 
main() { 
   var accounts = new HashMap(); 
   accounts['dept']='BA'; 
   accounts['name']='Kim'; 
   accounts['email']='[email protected]'; 
   print('Map after adding  entries :${accounts}'); 
}

=> output

Map after adding entries :{email: [email protected], dept: BA, name: Kim}

Adding Multiple Values to a HashMap

HashMap.addAll(Iterable)

Example

import 'dart:collection'; 
main() { 
   var accounts = new HashMap(); 
   accounts.addAll({'dept':'BA','email':'[email protected]'}); 
   print('Map after adding  entries :${accounts}'); 
}

=> output

Map after adding  entries :{email: [email protected], dept: BA} 

Removing Values from a HashMap

import 'dart:collection'; 
main() { 
   var accounts = new HashMap(); 
   accounts['dept'] = 'BA'; 
   accounts['name'] = 'Kim'; 
   accounts['email'] = '[email protected]'; 
   print('Map after adding  entries :${accounts}');
   accounts.remove('dept'); 
   print('Map after removing  entry :${accounts}');  
   accounts.clear(); 
   print('Map after clearing entries :${accounts}'); 
} 

=> output

Map after adding  entries :{email: [email protected], dept: BA, name: Kim} 
Map after removing  entry :{email: [email protected], name: Kim} 
Map after clearing entries :{}
# HashSet
Identifier = new HashSet() 

Adding Multiple Values to a HashSet

addAll() function allows adding multiple values to the HashSet.

import 'dart:collection'; 
void main() { 
   Set numberSet = new  HashSet(); 
   numberSet.addAll([10,20,30]); 
   print("Default implementation :${numberSet.runtimeType}"); 
   for(var no in numberSet){ 
      print(no); 
   } 
}

=> output 

Default implementation :_HashSet 
200 
300 
100 

Removing Values from a HashSet

remove() function removes the value passed to it.

clear() function removes all the entries from the HashSet.

import 'dart:collection'; 
void main() { 
   Set numberSet = new  HashSet(); 
   numberSet.addAll([10,20,30]); 
   print("Printing hashet.. ${numberSet}");  
   numberSet.remove(10); 
   print("Printing hashet.. ${numberSet}");  
   numberSet.clear(); 
   print("Printing hashet.. ${numberSet}"); 
} 

=> output 

Printing hashet.. {20, 30, 10} 
Printing hashet.. {20, 30} 
Printing hashet.. {}

Dart: Collection List Cheat Sheet

# Lists in Dart 

  • Fixed Length List − The list’s length cannot change at run-time.
  • Growable List − The list’s length can change at run-time.

# Example

void main() { 
   List logTypes = new List(); 
   logTypes.add("WARNING"); 
   logTypes.add("ERROR"); 
   logTypes.add("INFO");  
   
   // iterating across list 
   for(String type in logTypes){ 
      print(type); 
   } 
   
   // printing size of the list 
   print(logTypes.length); 
   logTypes.remove("WARNING"); 
   
   print("size after removing."); 
   print(logTypes.length); 
}

=> The output:

WARNING 
ERROR 
INFO 
3 
size after removing. 
2

Dart: Packages Cheat Sheet

# The important pub commands 

pub getIt helps to get all packages your application is depending on.
pub upgradeUpgrades all your dependencies to a newer version.
pub buildThis s used for building your web application and it will create a build folder, with all related scripts in it.
pub helpThis will give you help with all different pub commands.

Dart: Exceptions Cheat Sheet

# Built-in Dart exceptions include
DeferredLoadExceptionThrown when a deferred library fails to load.
FormatExceptionThe exception is thrown when a string or some other data does not have an expected format and cannot be parsed or processed.
IntegerDivisionByZeroExceptionThrown when a number is divided by zero.
IOExceptionBase class for all Inupt- Output related exceptions.
IsolateSpawnExceptionThrown when an isolate cannot be created.
TimeoutThrown when a scheduled timeout happens while waiting for an async result.
# The try/ on/ catch Blocks
try { 
   // code that might throw an exception 
}  
on Exception1 { 
   // code for handling exception 
}  
catch Exception2 { 
   // code for handling exception 
} 
# The Finally Block
try { 
   // code that might throw an exception 
}  
on Exception1 { 
   // exception handling code 
}  
catch Exception2 { 
   //  exception handling 
}  
finally { 
   // code that should always execute; irrespective of the exception 
}
# Throwing an Exception
throw new Exception_name()

Dart: Typedef Cheat Sheet

# Implement typedefs in a Dart program
  • Defining a typedef
typedef function_name(parameters)
  • Assigning a Function to a typedef Variable
type_def var_name = function_name
  • Invoking a Function
var_name(parameters) 

Dart: Libraries Cheat Sheet

# Importing a library in Dart

import 'URI'
import 'dart:io' 
import 'package:lib1/libfile.dart' 
import 'package: lib1/lib1.dart' show foo, bar;  
// Import only foo and bar. 

import 'package: mylib/mylib.dart' hide foo;  
// Import all names except foo

# Commonly used libraries

dart:ioFile, socket, HTTP, and other I/O support for server applications. This library does not work in browser-based applications. This library is imported by default.
dart:coreBuilt-in types, collections, and other core functionality for every Dart program. This library is automatically imported.
dart: mathMathematical constants and functions, plus a random number generator.
dart: convertEncoders and decoders for converting between different data representations, including JSON and UTF-8.
dart: typed_dataLists that efficiently handle fixed sized data (for example, unsigned 8 byte integers).