constructor in flutter code example

Example 1: constructor in dart

//Creating object.
void main(){
  SelfDrivingCar myLamb = SelfDrivingCar('Floride');
  myLamb.drive();
 
}

//Initializing class Car.
class Car {
  int numberofwheels = 4;
  
  void drive() {
    print('this is a car');
  }
}

//using Inheritance 
class SelfDrivingCar extends Car {
  String destination='k';
  
  SelfDrivingCar(String userDestination){ //constructor
    destination = userDestination;
  }
      //polymorphism.
  void drive() {
    super.drive();  // accessing parent's methods.
    
    print('sterring wheel to $destination');
    
  }
}

Example 2: fluter class constructor

class Customer {
  String name;
  int age;
  String location;

  // constructor
  Customer(String name, int age, String location) {
    this.name = name;
    this.age = age;
    this.location = location;
  }
}

Example 3: dart call constructor in constructor

class Chipmunk {
  String name;
  int fame;

  Chipmunk.named(this.name, [this.fame]);

  Chipmunk.famous1() : this.named('Chip', 1000);
  factory Chipmunk.famous2() {
    var result = new Chipmunk.named('Chip');
    result.fame = 1000;
    return result;
  }
}

Example 4: Flutter Constructor

Customer(String name, int age, String location) {
  this.name = name;
  this.age = age;
  this.location = location;
}

Customer(this.name, this.age) {
  this.name = name;
  this.age = age;
}

Example 5: constructor flutter

class Student{
  Student(int enNum){
    print(enNum);
  }
}

main(){
  var myStudent = new Student(15);
}

Tags:

Dart Example