## 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 (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() {
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();
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();
print(lst.isEmpty);
}  ```

=> output

`False  `

#### # isNotEmpty Method

```List.isNotEmpty
```
```void main() {
var lst = new List();
print(lst.isNotEmpty);
}  ```

=> output

`true  `

#### # length Method

`List.length `
```void main() {
var lst = new List();
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();
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();
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();
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

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

## Dart: Collection Queue Cheat Sheet

`Identifier = new Queue()`

Example

```import 'dart:collection';
void main() {
Queue queue = new Queue();
print("Default implementation \${queue.runtimeType}");

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}");
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();
print("Printing Q.. \${numQ}");
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();
print("Printing Q.. \${numQ}");
print("Printing Q.. \${numQ}");
} ```

It should produce the following output −

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

## Dart: Object Cheat Sheet

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 Maps Cheat Sheet

```void main() {
var details = new Map();
print(details);
}     ```

=> output

`{Usrname: admin, Password: [email protected]} `

## 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]';
}```

=> 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();
}```

=> 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]';
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();
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();
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();

// 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

## Dart: Exceptions Cheat Sheet

##### # 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