Dart
12 Notes
Map<int, String> _levels = <int, String>{ 0: 'All Levels', 1: 'Beginner', 2: 'Intermedidate', 3: 'Advanced' }; _levels.forEach((int value, String title) { items.add(new DropdownMenuItem( value: value.toString(), child: new Text(title), ));
You can define getters and setters whenever you need more control over a property than a simple field allows. For example, you can make sure a property’s value is valid: class MyClass { int _aProperty = 0; int get aProperty => _aProperty; set aProperty(int value) { if (value >= 0) { _aProperty = value; } } } You can also use a getter to define a computed property: class MyClass { List<int> _values = []; void addValue(int value) { _values.add(value); } // A computed property. int get count { return _values.length; } }
Cascades To perform a sequence of operations on the same object, use cascades (..). myObject.someMethod() It invokes someMethod() on myObject, and the result of the expression is the return value of someMethod(). Here’s the same expression with a cascade: myObject..someMethod() Although it still invokes someMethod() on myObject, the result of the expression isn’t the return value — it’s a reference to myObject! Using cascades, you can chain together operations that would otherwise require separate statements. For example, consider this code: var button = querySelector('#confirm'); button.text = 'Confirm'; button.classes.add('important'); button.onClick.listen((e) => window.alert('Confirmed!')); With cascades, the code becomes much shorter, and you don’t need the button variable: querySelector('#confirm') ..text = 'Confirm' ..classes.add('important') ..onClick.listen((e) => window.alert('Confirmed!'));
bool hasEmpty = aListOfStrings.any((s) => s.isEmpty); bool hasEmpty = aListOfStrings.any((s) { return s.isEmpty; }); ----------------------------------------------------------------
Dart has built-in support for lists, maps, and sets. You can create them using literals: final aListOfStrings = ['one', 'two', 'three']; final aSetOfStrings = {'one', 'two', 'three'}; final aMapOfStringsToInts = { 'one': 1, 'two': 2, 'three': 3, }; -------------------------------------------------------------------- Dart’s type inference can assign types to these variables for you. In this case, the inferred types are List<String>, Set<String>, and Map<String, int>. Or you can specify the type yourself: final aListOfInts = <int>[]; final aSetOfInts = <int>{}; final aMapOfIntToDouble = <int, double>{}; Specifying types is handy when you initialize a list with contents of a subtype, but still want the list to be List<BaseType>: final aListOfBaseType = <BaseType>[SubType(), SubType()]; --------------------------------------------------------------------
'${3 + 2}' '5' '${"word".toUpperCase()}' 'WORD' '$myObject' The value of myObject.toString()
?? Use ?? when you want to evaluate and return an expression IFF another expression resolves to null. exp ?? otherExp is similar to ((x) => x == null ? otherExp : x)(exp) ------------------------------------------------------------------------- ??= Use ??= when you want to assign a value to an object IFF that object is null. Otherwise, return the object. obj ??= value is similar to ((x) => x == null ? obj = value : x)(obj) ------------------------------------------------------------------------- ?. Use ?. when you want to call a method/getter on an object IFF that object is not null (otherwise, return null). obj?.method() is similar to ((x) => x == null ? null : x.method())(obj) You can chain ?. calls, for example: obj?.child?.child?.getter If obj, or child1, or child2 are null, the entire expression returns null. Otherwise, getter is called and returned. ------------------------------------------------------------------------- ?… Dart 2.3 brings in a spread operator (…) and with it comes a new null aware operator, ?... ! Placing ... before an expression inside a collection literal unpacks the result of the expression and inserts its elements directly inside the new collection. So now, these two are equivalent. List numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; and List lowerNumbers = [1, 2, 3, 4, 5]; List upperNumbers = [6, 7, 8, 9, 10]; List numbers = […lowerNumbers…upperNumbers]; To benefit from the new null aware operator, you can use it like this. List lowerNumbers = [1, 2, 3, 4, 5]; List upperNumbers = [6, 7, 8, 9, 10]; List numbers = […lowerNumbers?…upperNumbers]; which is the equivalent to List numbers = []; numbers.addAll(lowerNumbers); if(upperNumbers != null){ numbers.addAll(upperNumbers); } -------------------------------------------------------------------------
forEach() var fruits = [‘banana’, ‘pineapple’, ‘watermelon’]; fruits.forEach((fruit) => print(fruit)); // => banana pineapple watermelon ------------------------------------------------------------------------- map() var mappedFruits = fruits.map((fruit) => ‘I love $fruit’).toList(); print(mappedFruits); // => ['I love banana', ‘I love pineapple’, ‘I love watermelon’] ------------------------------------------------------------------------- contains() var numbers = [1, 3, 2, 5, 4]; print(numbers.contains(2)); // => true ------------------------------------------------------------------------- sort() numbers.sort((num1, num2) => num1 - num2); // => [1, 2, 3, 4, 5] ------------------------------------------------------------------------- reduce(), fold() Compresses the elements to a single value, using the given function. var sum = numbers.reduce((curr, next) => curr + next); print(sum); // => 15 const initialValue = 10; var sum2 = numbers.fold(initialValue, (curr, next) => curr + next); print(sum2); // => 25 ------------------------------------------------------------------------- every() Confirms that every element satisfies the test. List<Map<String, dynamic>> users = [ { “name”: ‘John’, “age”: 18 }, { “name”: ‘Jane’, “age”: 21 }, { “name”: ‘Mary’, “age”: 23 }, ]; var is18AndOver = users.every((user) => user[“age”] >= 18); print(is18AndOver); // => true var hasNamesWithJ = users.every((user) => user[“name”].startsWith('J')); print(hasNamesWithJ); // => false ------------------------------------------------------------------------- where(), firstWhere(), singleWhere() Returns a collection of elements that satisfy a test. // See the example above for the users list var over21s = users.where((user) => user[“age”] > 21); print(over21s.length); // => 1 var nameJ = users.firstWhere((user) => user[“name”].startsWith(‘J’), orElse: () => null); print(nameJ); // => {name: John, age: 18} var under18s = users.singleWhere((user) => user[“age”] < 18, orElse: () => null); print(under18s); // => null firstWhere() returns the first match in the list, while singleWhere() returns the first match provided there is exactly one match. ------------------------------------------------------------------------- take(), skip() Returns a collection while including or skipping elements. var fiboNumbers = [1, 2, 3, 5, 8, 13, 21]; print(fiboNumbers.take(3).toList()); // => [1, 2, 3] print(fiboNumbers.skip(5).toList()); // => [13, 21] print(fiboNumbers.take(3).skip(2).take(1).toList()); // => [3] ------------------------------------------------------------------------- List.from() Creates a new list from the given collection. var clonedFiboNumbers = List.from(fiboNumbers); print(‘Cloned list: $clonedFiboNumbers’); ------------------------------------------------------------------------- expand() Expands each element into zero or more elements. var pairs = [[1, 2], [3, 4]]; var flattened = pairs.expand((pair) => pair).toList(); print(‘Flattened result: $flattened’); // => [1, 2, 3, 4] var input = [1, 2, 3]; var duplicated = input.expand((i) => [i, i]).toList(); print(duplicated); // => [1, 1, 2, 2, 3, 3] -------------------------------------------------------------------------
List languages = new List(); languages.add('Python'); languages.add('Perl'); languages.add('Dart'); List short = languages.where((l) => l.length < 5).toList(); print(short); // [Perl, Dart] ------------------------------------------------------------------ var fruits = ['apples', 'oranges', 'bananas']; fruits.where((f) => f.startsWith('a')).toList(); //apples ------------------------------------------------------------------ _AnimatedMovies = AllMovies.where((i) => i.isAnimated).toList(); ------------------------------------------------------------------
class Student { int id = -1; String name; Student(this.id, this.name); // Parameterised Constructor Student.myCustomConstructor() { // Named Constructor print("This is my custom constructor"); } Student.myAnotherNamedConstructor(this.id, this.name); // Named Constructor void study() { print("${this.name} is now studying"); } void sleep() { print("${this.name} is now sleeping"); } }
void main() { print("CASE 1"); // CASE 1: When you know the exception to be thrown, use ON Clause try { int result = 12 ~/ 0; print("The result is $result"); } on IntegerDivisionByZeroException { print("Cannot divide by Zero"); } print(""); print("CASE 2"); // CASE 2: When you do not know the exception use CATCH Clause try { int result = 12 ~/ 0; print("The result is $result"); } catch (e) { print("The exception thrown is $e"); } print(""); print("CASE 3"); // CASE 3: Using STACK TRACE to know the events occurred before Exception was thrown try { int result = 12 ~/ 0; print("The result is $result"); } catch (e, s) { print("The exception thrown is $e"); print("STACK TRACE \n $s"); } print(""); print("CASE 4"); // CASE 4: Whether there is an Exception or not, FINALLY Clause is always Executed try { int result = 12 ~/ 3; print("The result is $result"); } catch (e) { print("The exception thrown is $e"); } finally { print("This is FINALLY Clause and is always executed."); } print(""); print("CASE 5"); // CASE 5: Custom Exception try { depositMoney(-200); } catch (e) { print(e.errorMessage()); } finally { // Code } } class DepositException implements Exception { String errorMessage() { return "You cannot enter amount less than 0"; } } void depositMoney(int amount) { if (amount < 0) { throw new DepositException(); } }
int age = 32; var age = 32; They're both the same. -------------------------------------------------------------------------- int result = 12 ~/ 4; // There will be a warning "A value of type double can't be assigned to int." int result = 12 ~/ 4; // This way it will return the result in form of integer. -------------------------------------------------------------------------- Final and Const: If you never want to change a value then use "final" and "const" keywords. final cityName = 'Tehran'; const PI = 3.14 The "final" variable can only be set once and it is initialized when accessed. The "const" variable is implicitly final but it is a compile-time constant, i.e. it is initialized during compilation. class Circle { final color = 'red'; static const PI = 3.14; // Only static fields can be declared as const. } -------------------------------------------------------------------------- Conditional Expressions - Ternary Operator: int a = 2; int b = 3; a < b ? print("$a is smaller") : print("$b is smaller"); smallerNumber = a < b ? a : b; -------------------------------------------------------------------------- Conditional Expressions -Ternary Operator: String name = 'Mohsen'; String nameToPrint = name ?? 'Hassani'; // It will print "Mohsen". String name; String nameToPrint = name ?? 'Hassani'; // It will print "Hassani". -------------------------------------------------------------------------- For Loop: List colorNames = ["Blue", "Yello", "Green", "Red"]; for (String color in colorNames) { print(color); } -------------------------------------------------------------------------- Do-While Loop: int i = 1; do { print('Hello'); i++; } while (i <= 10); int i = 1; do { if ( i % 2 == 0 ) { print('Hello'); } i++; } while (i <= 10); -------------------------------------------------------------------------- Break Keyword: myOuterLoop: for ( int i = 1; i <= 3; i++ ) { innerLoop: for ( int j = 1; j <= 3; j++ ) { print("$i $j"); if ( i == 2 && j == 2 ) { break myOuterLoop; } } -------------------------------------------------------------------------- Optional Positional Parameters in Functions: void printCountries(String name1, [String name2, String name3]) { print("$name1"); print("$name2"); print("$name3"); } printCountries("Iran") // Prints Iran, null, null -------------------------------------------------------------------------- Optional Named Parameters: int findVolume(int length, {int breadth, int height}) { print("Volume is ${length * breadth * height}"); } findVolume(10, breadth: 5, height: 20); -------------------------------------------------------------------------- Optional Default Parameters: int findVolume(int length, {int breadth = 2, int height = 20}) { print("Volume is ${length * breadth * height}"); } --------------------------------------------------------------------------