Question #7MediumDart Basics

Named constructer in flutter

#flutter

Answer

Overview

In Dart, a named constructor is an additional constructor defined with a specific name using

text
ClassName.name()
syntax. They are used to provide multiple ways to create an object with different initialization logic.


Default vs Named Constructor

dart
class 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

dart
void 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

FeatureDefaultNamedFactory
Syntax
text
Class()
text
Class.name()
text
factory Class.name()
Return typeAlways this classAlways this classCan be subtype/cached
MultipleOnly one✅ Many✅ Many

Common patterns:

text
fromJson()
,
text
fromMap()
,
text
fromString()
,
text
empty()
,
text
initial()
,
text
guest()
— named constructors make object creation expressive and semantic.