Dart

2018/09/30

Dart

1. 基础

1.1 变量

  1. var
  2. final 和 const

####1.2 Built-in-types

  • numbers
  • strings
  • booleans
  • lists (also known as arrays)
  • sets
  • maps
  • runes 符号 (for expressing Unicode characters in a string)
  • symbols

####

2. 特性

  1. 混用继承

    class A {
    }
    class B {
    }
       
    class C extends A with B {
    }
    
  2. 接口实现

    class A implements B {
    }
    abstract class B {
      void describe();
    }
    
  3. 异步Async

    const oneSecond = Duration(seconds: 1);
    Future<void> printWithDelay(String message) async {
      await Future.delayed(oneSecond);
      print(message);
    }
    
  4. Async*

    Stream<String> report(Spacecraft craft, Iterable<String> objects) async* {
      for (var object in objects) {
        await Future.delayed(oneSecond);
        yield '${craft.name} flies by $object';
      }
    }
    
  5. 异常

    // 抛出异常
    if (astronauts == 0) {
      throw StateError('No astronauts.');
    }
    // try on or catch(both)
    try {
      breedMoreLlamas();
    } on OutOfLlamasException {
      // A specific exception
      buyMoreLlamas();
    } on Exception catch (e) {
      // Anything else that is an exception
      print('Unknown exception: $e');
    } catch (e) {
      // No specified type, handles all
      print('Something really unknown: $e');
    }
    
  6. ?? ?.

    int a;
    print(a ??= 3); // print 3
    print(a ?? 5); // print 3
    print(null ?? 'This is null'); // print 'This is null'
       
    myObject?.someProperty
    /*<=>*/
    (myObject != null) ? myObject.someProperty : 'myObject is null'
    
  7. Collection—list, set, map

    final aListOfStrings = ['one', 'two', 'three'];
    final aSetOfStrings = {'one', 'two', 'three'};
    final aMapOfStringsToInts = {
      'one': 1,
      'two': 2,
      'three': 3,
    };
    final aListOfInts = <int>[];
    final aSetOfInts = <int>{};
    final aMapOfIntToDouble = <int, double>{};
    
  8. =>

    bool hasEmpty = aListOfStrings.any((s) => s.isEmpty);
    /*<=>*/
    bool hasEmpty = aListOfStrings.any((s) {
      return s.isEmpty;
    });
    
  9. 串联调用

    var button = querySelector('#confirm');
    button.text = 'Confirm';
    button.classes.add('important');
    button.onClick.listen((e) => window.alert('Confirmed!'));
    /*<=>*/
    querySelector('#confirm')
    ..text = 'Confirm'
    ..classes.add('important')
    ..onClick.listen((e) => window.alert('Confirmed!'));
    
  10. factory

    class Square extends Shape {}
    class Circle extends Shape {}
    class Shape {
      Shape();
      factory Shape.fromTypeName(String typeName) {
        if (typeName == 'square') return Square();
        if (typeName == 'circle') return Circle();
        print('I don\'t recognize $typeName');
        return null;
      }
    }
    
  11. 重定向构造函数, 没有重装

    class Automobile {
      String make;
      String model;
      int mpg;
      // The main constructor for this class.
      Automobile(this.make, this.model, this.mpg);
      // Delegates to the main constructor.
      Automobile.hybrid(String make, String model) : this(make, model, 60);
      // Delegates to a named constructor
      Automobile.fancyHybrid() : this.hybrid('Futurecar', 'Mark 2');
    }
    

2. 异步 Future + async + await

  1. 异步场景
    1. 从网上获取数据Fetching data over a network
    2. 读写DB Writing to a database
    3. 从文件中读数据 Reading data from a file
  2. 与同步接口对比

    // Synchronous
    String createOrderMessage () {
      var order = getUserOrder();
      return 'Your order is: $order';
    }
       
    Future<String> getUserOrder() {
      // Imagine that this function is
      // more complex and slow.
      return 
        Future.delayed(
          Duration(seconds: 4), () => 'Large Latte'); 
    }
       
    // Synchronous
    main() {
      print('Fetching user order...');
      print(createOrderMessage());
    }
       
    // 'Fetching user order...'
    // 'Your order is: Instance of _Future<String>'
    
    // Asynchronous
    Future<String> createOrderMessage () async {
      var order = await getUserOrder();
      return 'Your order is: $order';
    }
       
    Future<String> getUserOrder() {
      // Imagine that this function is
      // more complex and slow.
      return
       Future.delayed(
         Duration(seconds: 4), () => 'Large Latte');
    }
       
    // Asynchronous
    main() async {
      print('Fetching user order...');
      print(await createOrderMessage());
    }
       
    // 'Fetching user order...'
    // 'Your order is: Large Latte'
    

文内导航