
What is constructor in flutter and how is used step by step guide
In Flutter (and Dart, the language behind Flutter), a constructor is a special method used to create and initialize an object when a class is instantiated. It allows you to pass values to the class when creating an instance.
What is a Constructor?
A constructor is a function with the same name as the class, used to set up an object.
Basic Syntax:
class ClassName {
// Constructor
ClassName() {
// initialization code
}
}
Types of Constructors in Dart
- Default Constructor
- Parameterized Constructor
- Named Constructor
- Factory Constructor
Step-by-Step Guide: Using a Constructor in Flutter
Step 1: Create a Dart class
Let’s say you’re building a User
class.
class User {
String name;
int age;
// Constructor
User(String name, int age) {
this.name = name;
this.age = age;
}
}
this.name = name;
means the class propertyname
gets the value passed asname
in the constructor.
Step 2: Create an Object Using the Constructor
You can now use the constructor to create an instance of the class:
void main() {
User user1 = User("Alice", 25);
print(user1.name); // Output: Alice
print(user1.age); // Output: 25
}
Alternative: Shorthand Constructor (Cleaner Syntax)
Dart allows a shorter way to write the constructor:
class User {
String name;
int age;
User(this.name, this.age);
}
This does the same as the longer version above but is more concise.
Example in a Flutter Widget
Let’s see how constructors are used in Flutter widgets.
Step 1: Create a StatelessWidget with a Constructor
import 'package:flutter/material.dart';
class GreetingCard extends StatelessWidget {
final String message;
// Constructor
GreetingCard({required this.message});
@override
Widget build(BuildContext context) {
return Center(
child: Text(
message,
style: TextStyle(fontSize: 24),
),
);
}
}
Step 2: Use It in Your main.dart
void main() {
runApp(MaterialApp(
home: Scaffold(
body: GreetingCard(message: "Hello from Flutter!"),
),
));
}
Types of Constructors Explained
1. Default Constructor
class MyClass {
MyClass() {
print("Default constructor called");
}
}
2. Parameterized Constructor
class MyClass {
int x;
MyClass(this.x);
}
3. Named Constructor
class MyClass {
int x;
MyClass.named(this.x); // Named constructor
}
4. Factory Constructor (used for returning cached instances, etc.)
class Logger {
static final Logger _instance = Logger._internal();
factory Logger() {
return _instance;
}
Logger._internal(); // private named constructor
}
Summary
Type | Description | Syntax |
---|---|---|
Default | No arguments | ClassName() |
Parameterized | Takes arguments | ClassName(this.param) |
Named | Custom named constructors | ClassName.namedConstructor() |
Factory | Used when returning an existing object | factory ClassName() |
Pingback: Dart basic programs mostly asked in interviews - Dheeraj Hitech
Pingback: Flutter key points mostly asked in flutter interviews - Dheeraj Hitech