Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn Dart Constructor

Constructors in Dart are special methods within a class used for initializing objects. They allow you to provide initial values for an object's fields when it is created. In Dart, constructors have the same name as the class and can be overloaded, meaning you can define multiple constructors within a class. Dart supports various types of constructors, including:

Default Constructor

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


Parameterized Constructor:

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


Named Constructor:

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


Factory Constructor:

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 _cache = {};
factory Logger(String name) {
return _cache.putIfAbsent(
name,
() => Logger._internal(name),
);
}
Logger._internal(this.name);
}

Constant Constructor:

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 }






Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java