dart Dart Factory构造函数

Dart Factory构造函数

Dart Factory Constructor.dart
class Employee {
  String name;
  factory Employee(int type) {
    switch (type) {
      case 1:
        return new Admin('admin');

      case 2:
        return new Accountant('accountant');

      default:
        return new Worker('worker');
    }
  }

  Employee._(name) {
    this.name = name;
  }
}

class Worker extends Employee {
  Worker(String name) : super._(name);
}

class Accountant extends Employee {
  Accountant(String name) : super._(name);
}

class Admin extends Employee {
  Admin(String name) : super._(name);
}

/******** Implementation ********/
Employee emp = new Employee(1);
print(emp.name);

/******** Output 
   admin
*/

dart Dart命名为构造函数

Dart命名为构造函数

Dart Named Constructor.dart
class Employee {
  String name;
  int age;
  Employee.name(this.name);
  
  Employee.age(this.age);
}
/******** Implementation ********/
Employee emp1 = new Employee.name('Scott');
print(emp1.name);
  
Employee emp2 = new Employee.age(28);
print(emp2.age);
  
/******** Output 
  Scott
  28
*/

dart Dart Normal Constructor

Dart Normal Constructor

Dart Normal Constructor.dart
class Employee {
  Employee(); // <-- Constructor

  void printAbout() {
    print('Employee class.');
  }
}

class Accountant {
  String name;
  int age;
  
  Accountant(String name, int this.age) {
    this.name = name; 
  }

  void printAbout() {
    print(name);
  }
}


/******** Implementation ********/
Employee employee = new Employee();
employee.printAbout();

Accountant emp2 = new Accountant('Freddy',32);
print(emp2.name);
print(emp2.age);

/******** Output
    Employee class.
    Freddy
    32
*/

dart Dart Async

Dart Async

Dart Async.dart
import 'dart:async';

const greeting = 'Hello Sir !! How are you doing today ?';
const takesSomeTime = Duration(seconds: 3);

Future<String> startAConversation() async {
  var response = await aVeryTimeConsumingTask();  
  return response;
}

Future<String> aVeryTimeConsumingTask() =>
    Future.delayed(takesSomeTime, () => greeting);

/******* Implementation *******/
startAConversation()
    .then((String words) => print(words));
/******** Output [After 3 seconds]
    Hello Sir !! How are you doing today ?
*/

dart 飞镖类型def

飞镖类型def

Dart Type def.dart
typedef SaySomething(String person, String message);

Shout(String person, String message){
  print('$person: $message');
}

Speak(String person, String message){
  print('$person: $message');
}

Whisper(String person, String message){
  print('$person: $message');
}

/******** Implementation ********/
SaySomething say = Shout;
say('Johnny','Hey Bill !!');
  
say = Speak;
say('Bill', 'Yes, What`s up Johnny Boy !!!');
  
say = Whisper;
say('Librarian', 'Shhhhh!! Don`t make noise !!');

/******** Output 
    Johnny: Hey Bill !!
    Bill: Yes, What`s up Johnny Boy !!!
    Librarian: Shhhhh!! Don`t make noise !!
*/

dart Dart异常处理

Dart异常处理

Dart Exception Handling.dart
/******** Simple Try Catch ********/
try {
   // Statement
   
   throw new Exception('You can even throw your own exception');
}
catch(e) {
  // Handle exception
}


/******** Try On ********/
try {
   // Statement
}
on IntegerDivisionByZeroException {
 // Handle exception
}
on IOException catch(e) {
  // Handle exception
}

/******** Try Catch Finally ********/
try {
   // Statement
}
catch(e) {
  // Handle exception
}
finally {
}


/******** Custom Exception ********/
class MyException implements Exception {
  MyException(String msg) : super(msg);
}

/******** Overall Implementations ********/
class TooOldException extends StateError {
  TooOldException(String msg) : super(msg);
}

class SimpleException implements Exception {
   String errMsg() => 'Almost the perfect age !!'; 
}

void validateAge(int age) {
  try {
    if (age < 3) {
      throw new Exception("Just a child !!");
    } else if (age >= 3 && age <= 12) {
      throw new Exception();
    } else if(age>12 && age <15){
      throw new SimpleException();
    } else if(age>=15 && age <90){
        print('This dude is Ok to pass !!');
    }else if (age > 90) {
      throw new TooOldException('Too old');
    }
        
  } on TooOldException  { // <-- Without catch
    print('This guy is too old !!');
  } on SimpleException catch(e) { // <-- With catch
    print(e.errMsg());
  }
  catch (ex) { 
    print(ex.toString());
  } finally {
  }
}

validateAge(2);
validateAge(4);
validateAge(13);
validateAge(92);
validateAge(18);

/******** Output 
    Exception: Just a child !!
    Exception
    Almost the perfect age !!
    This guy is too old !!
    This dude is Ok to pass !!
*/

dart Dart Spread Operators

Dart Spread Operators

Dart Spread Operators.dart
var fruits = ['apple', 'banana', 'grape'];
var more_fruits = ['peach','strawberry'];
var all_fruits = ['guava','coconut', ...fruits, ...more_fruits];
print(all_fruits);

/******** Output 
[guava, coconut, apple, banana, grape, peach, strawberry]
*/

/******** Null-aware Spread Operator ********/
var random_fruits = null;
var only_good_ones = [...fruits,...?random_fruits];
print(only_good_ones);
/******** Output 
[apple, banana, grape]
*/


/******** Conditional ********/
bool loves_all = false;
var johnnys_fav = [
  'guava','coconut', 
  ...fruits,
  if(loves_all)
     ... more_fruits
];
 
print(johnnys_fav);
/******** Output 
[guava, coconut, apple, banana, grape]
*/

dart Dart Generics

Dart Generics

Dart Generics.dart

List<String> fruits = new List<String>(); 
fruits.add("apple"); 
fruits.add("banana"); 
fruits.add("mango"); 
fruits.add(45); // <- This will give an error if used.
  
for (String fruit in fruits) { 
   print(fruit); 
} 
/******** Output
   apple
   banana
   mango
*/

/******** Other Implementations *******/
Queue<int> queue = new Queue<int>(); 
Set<int>numberSet = new Set<int>(); 
Map<String,String> employee= {
  'Name':'Johny',
  'Gender': 'Male'
}; 

dart 飞镖队列

飞镖队列

Dart Queue.dart
import 'dart:collection'; 

Queue queue = new Queue(); 
queue.add({'Name':'Goku'});
queue.add(23);
queue.add(45);
queue.add(true);
queue.add('potatoes');
   
for(var data in queue){ 
   print(data); 
} 

/******* Output
   {Name: Goku}
   23
   45
   true
   potatoes
*/

/****** Methods ********/
queue.addFirst(<data>) // Add at the beginning
queue.addLast(<data>) // Add at the end

dart Dart HashSet

Dart HashSet

Dart HashSet.dart
import 'dart:collection'; 

Set myRecords = new  HashSet(); 

myRecords.add({'Name':'Goku'});
myRecords.add(23);
myRecords.add(45);
myRecords.add(true);
myRecords.add('potatoes');
  
for(var data in myRecords){ 
   print(data); 
}

/******** Output
  potatoes
  23
  45
  true
  {Name: Goku}
*/