美文网首页
flutter 构造器

flutter 构造器

作者: 充满活力的早晨 | 来源:发表于2019-03-25 10:35 被阅读0次

    写了半天的dart ,结果呢,dart类的构造器写法和规则还不熟悉,有点搓。因此特此写篇博客,记录下flutter 构造器,加深记忆。

    构造器的创建

    flutter的构造器是通过创建一个命名和类名相同的方法生成的。
    例如

    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;
    
      Point(num x, num y) {
        // There's a better way to do this, stay tuned.
        this.x = x;
        this.y = y;
      }   
      
      Point(num x){
        
      }
    }
    

    不能同时函数两个point 构造函数

    要是只是单纯的给变量赋值,我们可以这样写

    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;
    //   }  
      ///等同于上面的写法
      Point(this.x ,this.y);   
    }
    

    默认构造函数

    要是我们在类中不写构造函数,类会有默认构造函数,就是不带参数的类名构造函数。如果类是继承关系的,那么该构造函数是继承父类的默认构造函数的
    如下

    class Point {
      num x, y;
    // 默认构造函数,默认可以不写
      Point();   
    }
    

    这里需要注意,一旦我们创建了构造函数,我们就不能调用默认构造函数了。同名函数只能有一个。

    class Point {
      num x, y;
    // 默认构造函数,默认可以不写
      Point(this.x, this.y);   
    }
    
    void main(){
    //报错 2 required argument(s) expected, but 0 found.
       Point();
    }
    

    构造函数是不能继承的

    构造函数只给当前类提供,子类是不能继承父类的构造函数的

    class Point {
    num y;
    // 默认构造函数,默认可以不写
    //   Point(this.x, this.y);   
    }
    
    class RectPoint extends Point{
        num x, y;
        RectPoint(this.x); 
    }
    
    void main(){
      RectPoint();
    }
    

    我们让子类RectPoint 继承Point ,但是我们调用父类的Point的默认构造方法Point();这报错,编译不过。

    自定义构造函数

    我们自定义构造函数必须明确的进行声明。就是前面要有类名了。如下

    class Point {
      num x, y;
    
      Point(this.x, this.y);
    
      // Named constructor
      Point.origin() {
        x = 0;
        y = 0;
      }
      
      Point.leftOrigin(num x){
        this.x= 0;
        this.x-= 5;
      }
    }
    

    自定义构造函数可以创建多个.

    这里需要注意,子类也是没法继承父类的自定义构造方法的。
    自定义构造函数一旦创建也会覆盖掉原来的默认构造函数。子类就没办法继承默认构造函数了。子类只能选择父类自定义构造哈市的一个

    如何继承父类非默认的构造器

    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';
    }
    

    我们必须在子类构造器后面明确的指定我们继承了父类的哪个构造器。

    相关文章

      网友评论

          本文标题:flutter 构造器

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