If you don't explicitly define a constructor in your class, Dart provides a default constructor for you.
The default constructor initializes instance variables to their default values (null for object types, 0 for numeric types, false for boolean, etc.).
If you define any constructors (other than the default), Dart does not provide a default constructor.
class Person {
String name;
int age;
}
Allows you to initialize instance variables with provided values when creating an object.
You can have multiple parameterized constructors, known as constructor overloading, by using named constructors.
class Person {
String name;
int age;
// Parameterized Constructor
Person(this.name, this.age);
}
Allows you to define multiple constructors with different names.
Useful for providing different ways to construct an object or initializing it based on different parameters.
class Person {
String name;
int age;
// Named Constructor
Person.fromMap(Map< String, dynamic> map) {
name = map['name'];
age = map['age'];
}
}
A factory constructor is used to return an instance of the class from within the constructor itself.
It can be used to return an instance of a subclass, a cached instance, or any other custom logic.
class Logger {
final String name;
static final Map
factory Logger(String name) {
return _cache.putIfAbsent(
name,
() => Logger._internal(name),
);
}
Logger._internal(this.name);
}
A constant constructor is used to create compile-time constant objects.
All fields in the class must be final and have a constant value, and the constructor must not have any parameters that are not final.
class Constants {
final int value;
const Constants(this.value);
}
void main() {
const constantObj = Constants(5); // Creates a compile-time constant object
}