class constructor in dart code example

Example 1: dart this constructor

class MyClass {
  int param1;
  MyClass(this.param1);
}
final obj = MyClass(100);

class MyClassNamed {			// with named parameters
  int param1;
  MyClassNamed({required this.param1});
}
final objNamedParam = MyClassNamed(param1: 100);

Example 2: dart constructor

void main() {
  Human jenny = Human(height1 :15);
    print(jenny.height);
  
  Human jerry = Human(height1: 20);
    print(jerry.height);
}

class Human {
  double height = 0;
  
  Human({height1 = 0}) { // constructor = initializes values of properties in the class.
    this.height = height1;
  }
  
}

Tags:

Misc Example