美文网首页
Dart学习笔记

Dart学习笔记

作者: 没头脑和挺高兴 | 来源:发表于2019-10-18 23:08 被阅读0次

    Hello World

    • save basic.dart
    • dart basic.dart
       // Define a function.
       printInteger(int aNumber) {
       print('The number is $aNumber.'); // Print to console.
       }
       // This is where the app starts executing.
       main() {
       var number = 42; // Declare and initialize a variable.
       printInteger(number); // Call a function.
       } 
    

    原则

    • 任何都是一个对象
    • dart是强类型的
    • 支持泛型
    • 支持顶层函数
    • 支持顶层变量
    • 没有访问限制符,使用_开头的来表示私有
    • 两种问题,异常和错误

    基本语法

    • 变量
      • var name='Bob'
      • String name='Bob';
      • dynamic name='Bob';
    • 默认值
      • 默认为null
    • final 和const
      • final和const初始化后都不能变化
      • const第一次可以计算出来
    • 内置类型
      • numbers
      • strings
      • booleans
      • lists
      • maps
      • runs
      • symbols
    • Numbers
      • int
        • -263 263-1
      • double
    • Strings
      • 'aaa'
      • "aaa"
      • """aaa"""
      • r'abc'
    • Booleans
    • List
      • var list = [1, 2, 3];
    • Maps
            var gifts = Map();
            gifts['first'] = 'partridge';
            gifts['second'] = 'turtledoves';
            gifts['fifth'] = 'golden rings';
            var nobleGases = Map();
            nobleGases[2] = 'helium';
            nobleGases[10] = 'neon';
            nobleGases[18] = 'argon';
            var gifts = {'first': 'partridge'};
            gifts['fourth'] = 'calling birds'; ​​
            ​
            void doStuff(
                {List<int> list = const [1, 2, 3],
                Map<String, String> gifts = const {
                  'first': 'paper',
                  'second': 'cotton',
                  'third': 'leather'
                }}) {
              print('list:  $list');
              print('gifts: $gifts');
            }
    

    Functions

    • 可选的参数
    • 可选的参数名
    • 可忽略的参数
    • 参数默认值
    • 函数赋值给变量
    • 函数作为参数传入
    • 匿名函数,作为闭包使用
                var list = ['apples', 'bananas', 'oranges'];
                list.forEach((item) {
                print('${list.indexOf(item)}: $item');
                });​​ 
    
    • 闭包

               Function makeAdder(num addBy) {
                  return (num i) => addBy + i;
                }
                void testClosure() {
                 var add2=makeAdder(2);
                  var add4 = makeAdder(4);
                  print(add2(3));
                  print(add4(5));
                }
      
    
    #  类型操作符
    * as typecast
    * is
    * is!
    *  赋值操作符
    * =
    * ??= 避免空指针
    *  其他操作符
    * () 函数
    * [] list访问
    * . 方法访问
    * ?. 条件
    *  控制语句
    * if
                if (isRaining()) {
                you.bringRainCoat();
                } else if (isSnowing()) {
                you.wearJacket();
                } else {
                car.putTopDown();
                } 
        * if
        * else if
        * else
    * for
    * while
        *  break
        *  switch
                var command = 'OPEN';
                switch (command) {
                case 'CLOSED':
                executeClosed();
                break;
                case 'PENDING':
                executePending();
                break;
                case 'APPROVED':
                executeApproved();
                break;
                case 'DENIED':
                executeDenied();
                break;
                case 'OPEN':
                executeOpen();
                break;
                default:
                executeUnknown();
                }
        *  assert
    *  异常
        *  Throw
                throw FormatException('Expected at least 1 section'); 
        *  try
                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');
                } 
        *  catch
        *  finally
                try {
                breedMoreLlamas();
                } catch (e) {
                print('Error: $e'); // Handle the exception first.
                } finally {
                cleanLlamaStalls(); // Then clean up.
                } 
    *  类
        *  类成员
            *  p.y = 3
            *  p?.=4
        *  构造函数
                var p1 = Point(2, 2);
                var p2 = Point.fromJson({'x': 1, 'y': 2});
        *  实例变量
                class Point {
                num x; // Declare instance variable x, initially null.
                num y; // Declare y, initially null.
                num z = 0; // Declare z, initially 0.
                }
        *  构造函数
                class Point {
                num x, y;
                Point(num x, num y) {
                // There's a better way to do this, stay tuned.
                this.x = x;
                this.y = y;
                }
                }
            *  新的构造方法
                    class Point {
                    num x, y;
                    // Syntactic sugar for setting x and y
                    // before the constructor body runs.
                    Point(this.x, this.y);
                    } 
            *  默认构造函数没有参数
            *  构造函数不能被继承,需要显式调用
            *  名字构造函数
                    class Point {
                    num x, y;
                    Point(this.x, this.y);
                    // Named constructor
                    Point.origin() {
                    x = 0;
                    y = 0;
                    }
                    } 
        *  父类构造函数初始化
                class Person {
                  String firstName;
                  Person.fromJson(Map data) {
                    print('in Person');
                  }
                }
                class Employee extends Person {
                  // Person does not have a default constructor;
                  // you must call super.fromJson(data).
                  Employee.fromJson(Map data) : super.fromJson(data) {
                    print('in Employee');
                  }
                }
                main() {
                  var emp = new Employee.fromJson({});
                  // Prints:
                  // in Person
                  // in Employee
                  if (emp is Person) {
                    // Type check
                    emp.firstName = 'Bob';
                  }
                  (emp as Person).firstName = 'Bob';
                }
            *  初始化列表
                    Point.fromJson(Map<String, num> json)
                    : x = json['x'],
                    y = json['y'] {
                    print('In Point.fromJson(): ($x, $y)');
                    }
            *  初始化列表的例子
                    import 'dart:math';
                    class Point {
                      final num x;
                      final num y;
                      final num distanceFromOrigin;
                      Point(x, y)
                          : x = x,
                            y = y,
                            distanceFromOrigin = sqrt(x * x + y * y);
                    }
                    main() {
                      var p = new Point(2, 3);
                      print(p.distanceFromOrigin);
                    } 
            *  多个构造函数的传递实现,为了减少重复代码
                    class Point {
                    num x, y;
                    // The main constructor for this class.
                    Point(this.x, this.y);
                    // Delegates to the main constructor.
                    Point.alongXAxis(num x) : this(x, 0);
                    }
            *  构造函数工厂
                    class Logger {
                    final String name;
                    bool mute = false;
                    // _cache is library-private, thanks to
                    // the _ in front of its name.
                    static final Map<String, Logger> _cache =
                    <String, Logger>{};
                    factory Logger(String name) {
                    if (_cache.containsKey(name)) {
                    return _cache[name];
                    } else {
                    final logger = Logger._internal(name);
                    _cache[name] = logger;
                    return logger;
                    }
                    }
                    Logger._internal([this.name](http://this.name/));
                    void log(String msg) {
                    if (!mute) print(msg);
                    }
                    }
                *  factory关键字
                *  不是创建一个新的,是根据传入参数重用已有的.
                *  使用方法
                        var logger = Logger('UI');
                        logger.log('Button clicked');
        *  方法
            *  是类的一个函数
                    import 'dart:math';
                    class Point {
                    num x, y;
                    Point(this.x, this.y);
                    num distanceTo(Point other) {
                    var dx = x - other.x;
                    var dy = y - other.y;
                    return sqrt(dx * dx + dy * dy);
                    }
                    }
            *  get和set函数
                    class Rectangle {
                    num left, top, width, height;
                    Rectangle(this.left, this.top, this.width, this.height);
                    // Define two calculated properties: right and bottom.
                    num get right => left + width;
                    set right(num value) => left = value - width;
                    num get bottom => top + height;
                    set bottom(num value) => top = value - height;
                    }
                    void main() {
                    var rect = Rectangle(3, 4, 20, 15);
                    assert(rect.left == 3);
                    rect.right = 12;
                    assert(rect.left == -8);
                    } 
        *  抽象方法
                abstract class Doer {
                // Define instance variables and methods...
                void doSomething(); // Define an abstract method.
                }
                class EffectiveDoer extends Doer {
                void doSomething() {
                // Provide an implementation, so the method is not abstract here...
                }
                }
            *  abstract
            *  没有实现
            *  需要子类完成实现
        *  抽象类
                // This class is declared abstract and thus
                // can't be instantiated.
                abstract class AbstractContainer {
                // Define constructors, fields, methods...
                void updateChildren(); // Abstract method.
                }
        *  隐含的接口
                // A person. The implicit interface contains greet().
                class Person {
                // In the interface, but visible only in this library.
                final _name;
                // Not in the interface, since this is a constructor.
                Person(this._name);
                // In the interface.
                String greet(String who) => 'Hello, $who. I am $_name.';
                }
                // An implementation of the Person interface.
                class Impostor implements Person {
                get _name => '';
                String greet(String who) => 'Hi $who. Do you know who I am?';
                }
                String greetBob(Person person) => person.greet('Bob');
                void main() {
                print(greetBob(Person('Kathy')));
                print(greetBob(Impostor()));
                } 
            *  关键字 implements
            *  所有类都可以通过implements来重新实现另外一个类
            *  需要重新实现所有方法
        *  继承类
                class Television {
                void turnOn() {
                _illuminateDisplay();
                _activateIrSensor();
                }
                // ···
                }
                class SmartTelevision extends Television {
                void turnOn() {
                super.turnOn();
                _bootNetworkInterface();
                _initializeMemory();
                _upgradeApps();
                }
                // ···
                }
            *  关键字 extends
            *  所有类可以通过extends扩展另外一个类
            *  需要实现一个构造函数
        *  重写类的方法
                class SmartTelevision extends Television {
                @override
                void turnOn() {...}
                // ···
                }
            *  @override
            *  super 可以调用父类的代码
        *  重写操作符
                class Vector {
                final int x, y;
                Vector(this.x, this.y);
                Vector operator +(Vector v) => Vector(x + v.x, y + v.y);
                Vector operator -(Vector v) => Vector(x - v.x, y - v.y);
                // Operator == and hashCode not shown. For details, see note below.
                // ···
                }
                void main() {
                final v = Vector(2, 3);
                final w = Vector(2, 2);
                assert(v + w == Vector(4, 5));
                assert(v - w == Vector(0, 1));
                }
        *  重写noSuchMethod方法
                class A {
                // Unless you override noSuchMethod, using a
                // non-existent member results in a NoSuchMethodError.
                @override
                void noSuchMethod(Invocation invocation) {
                print('You tried to use a non-existent member: ' +
                '${invocation.memberName}');
                }
                }
    *  Enumberated Types
        *  使用
                enum Color { red, green, blue }
            *  关键字enum
                    var aColor = Color.blue;
                    switch (aColor) {
                    case Color.red:
                    print('Red as roses!');
                    break;
                    case Color.green:
                    print('Green as grass!');
                    break;
                    default: // Without this, you see a WARNING.
                    print(aColor); // 'Color.blue'
                    } 
    *  mixins
        *  关键字with
        *  需要好好理解?
    *  类的变量和方法
        *  static == 跟类绑定不是跟实例绑定
        *  静态方法
                import 'dart:math';
                class Point {
                num x, y;
                Point(this.x, this.y);
                static num distanceBetween(Point a, Point b) {
                var dx = a.x - b.x;
                var dy = a.y - b.y;
                return sqrt(dx * dx + dy * dy);
                }
                }
                void main() {
                var a = Point(2, 2);
                var b = Point(4, 4);
                var distance = Point.distanceBetween(a, b);
                assert(2.8 < distance && distance < 2.9);
                print(distance);
                } 
    *  泛型
        *  泛型就是类型的重用
        *  变量是方法的重用
        *  集合泛型例子
                var names = <String>['Seth', 'Kathy', 'Lars'];
                var pages = <String, String>{
                'index.html': 'Homepage',
                'robots.txt': 'Hints for web robots',
                'humans.txt': 'We are people, not machines'
                };
        *  限制参数类型
                class Foo<T extends SomeBaseClass> {
                // Implementation goes here...
                String toString() => "Instance of 'Foo<$T>'";
                }
                var someBaseClassFoo = Foo<SomeBaseClass>();
                var extenderFoo = Foo<Extender>();​​
                ​​​
    *   使用类
    *  import 'dart:html';
    *  import 'package:test/test.dart';
    *  pub 管理工具
    *  import 'package:lib2/lib2.dart' as lib2;
    *  引入某一部分
        *  import 'package:lib1/lib1.dart' show foo;
        *  import 'package:lib2/lib2.dart' hide foo;
    *  延迟加载
        *  import 'package:greetings/hello.dart' deferred as hello;
    

    相关文章

      网友评论

          本文标题:Dart学习笔记

          本文链接:https://www.haomeiwen.com/subject/rftgoftx.html