constructors dart code example
Example 1: dart this constructor
class MyClass {
int param1;
MyClass(this.param1);
}
final obj = MyClass(100);
class MyClassNamed {
int param1;
MyClassNamed({required this.param1});
}
final objNamedParam = MyClassNamed(param1: 100);
Example 2: constructor in dart
void main(){
SelfDrivingCar myLamb = SelfDrivingCar('Floride');
myLamb.drive();
}
class Car {
int numberofwheels = 4;
void drive() {
print('this is a car');
}
}
class SelfDrivingCar extends Car {
String destination='k';
SelfDrivingCar(String userDestination){
destination = userDestination;
}
@override
void drive() {
super.drive();
print('sterring wheel to $destination');
}
}
Example 3: fluter class constructor
class Customer {
String name;
int age;
String location;
Customer(String name, int age, String location) {
this.name = name;
this.age = age;
this.location = location;
}
}
Example 4: named constructor dart
class Person {
String name;
int age;
Person({this.name = '', this.age = 0});
}
void main() {
Person person1 = Person(name: "Raaj", age: 35);
print(person1.age);
}
Example 5: 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 6: 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;
}