Answer
Overview
In Dart, a named constructor is an additional constructor defined with a specific name using
text
ClassName.name()Default vs Named Constructor
dartclass User { final String name; final String email; final String role; // Default constructor User({required this.name, required this.email, this.role = 'user'}); // Named constructor — creates a guest user User.guest() : name = 'Guest', email = 'guest@example.com', role = 'guest'; // Named constructor — creates from JSON/Map User.fromJson(Map<String, dynamic> json) : name = json['name'], email = json['email'], role = json['role'] ?? 'user'; // Named constructor — creates an admin User.admin({required String name, required String email}) : name = name, email = email, role = 'admin'; }
Using Named Constructors
dartvoid main() { // Default final user1 = User(name: 'Alice', email: 'alice@example.com'); // Named — guest final guest = User.guest(); print(guest.name); // Guest print(guest.role); // guest // Named — from JSON final json = {'name': 'Bob', 'email': 'bob@example.com', 'role': 'admin'}; final user2 = User.fromJson(json); print(user2.name); // Bob // Named — admin final admin = User.admin(name: 'Carol', email: 'carol@example.com'); print(admin.role); // admin }
Named Constructor in Flutter
dart// Common use: fromJson / fromMap class Product { final int id; final String name; final double price; Product({required this.id, required this.name, required this.price}); // Parse from API response factory Product.fromJson(Map<String, dynamic> json) { return Product( id: json['id'], name: json['name'], price: (json['price'] as num).toDouble(), ); } // Empty/placeholder product Product.empty() : id = 0, name = '', price = 0.0; // Copy with modifications Product copyWith({String? name, double? price}) { return Product(id: id, name: name ?? this.name, price: price ?? this.price); } }
Named vs Factory Constructor
dart// Named constructor — always creates a new instance of this class User.guest() : ...; // Factory constructor — can return existing instance or a subtype factory User.fromCache(String id) { return _cache[id] ?? User(name: 'Unknown', email: ''); }
Summary
| Feature | Default | Named | Factory |
|---|---|---|---|
| Syntax | text | text | text |
| Return type | Always this class | Always this class | Can be subtype/cached |
| Multiple | Only one | ✅ Many | ✅ Many |
Common patterns:
,textfromJson(),textfromMap(),textfromString(),textempty(),textinitial()— named constructors make object creation expressive and semantic.textguest()