DartBasic 2 min read

Dart constructors and factories: validate a product model

Use named constructors, initializer lists, factories and const objects for deliberate model creation.

On this page

A product model should not be half-valid after construction. Keep validation near the creation boundary and choose a constructor name that explains the input format. A factory can validate or choose an implementation before returning an instance.

Worked example

Language requirement: Dart 3.0 or later. This complete example uses browser-supported libraries.

main.dart
class Product {
  const Product._(this.sku, this.pricePaise);
  final String sku;
  final int pricePaise;

  factory Product.fromInput(String sku, int pricePaise) {
    final clean = sku.trim();
    if (clean.isEmpty || pricePaise < 0) {
      throw ArgumentError('A product needs an SKU and non-negative price.');
    }
    return Product._(clean, pricePaise);
  }
}

void main() {
  final product = Product.fromInput(' CABLE-1 ', 15000);
  print('${product.sku}: ${product.pricePaise} paise');
}

Follow the data and control flow

The factory normalizes and validates input before calling the private generative constructor. Fields are final, so a created instance cannot later receive a different SKU or price through reassignment. The private constructor is library-private, not a security boundary against other code in the same library.

An initializer list runs before the constructor body and is useful for derived final fields or superclass initialization. A const constructor permits compile-time instances when the arguments and context meet const requirements; it does not mean every invocation is necessarily canonicalized.

A mistake to avoid

An assert in a constructor is a development check, not production validation. Use an explicit failure for externally supplied invalid input. Also remember that a factory cannot access this before returning an object because it is not operating on a newly initialized instance in that way.

Practice and verification

Add an empty-SKU case and a negative price case. Verify both fail before any usable product is returned. Add a named constructor for a free sample and explain which invariants should remain identical.

How this topic connects

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.